//
//  SyncManager.m
//  leo
//
//  Created by 常艳 on 15/8/26.
//  Copyright (c) 2015年 mdx. All rights reserved.
//由UI层直接调用，处理UI层所有和网络有关的操作

#import "SyncManager.h"
#import "AppDelegate.h"
#import "VoiceConverter.h"
@import AVFoundation;
@import AudioToolbox;

@implementation SyncManager
+(SyncManager *)sharedSingleton
{
    static SyncManager *syncManager;
    @synchronized(self)
    {
        if(syncManager==NULL)
            syncManager=[[SyncManager alloc] init];
    }
    return syncManager;
}
-(id)init
{
    
    self=[super init];
    self.theRequeseter=[[HttpRequester alloc] init];
    self.theDbHelper=[[DBHelper alloc] init];
    self.theManager=[[DataManager alloc] init];
    return self;
}
-(void)dealloc
{
    self.theRequeseter=NULL;
    self.theDbHelper=NULL;
    self.theManager=NULL;
}
//注册绑定相关接口
/*手机申请SMS验证码:ok
 参数:
 phone:11位电话号码，callback:请求返回时的回调函数,type:0表示注册请求短信验证码、1表示忘记密码请求短信验证码
 返回值:
 result:表示请求结果，SUCESS:请求成功、FAIL:请求失败
 retValue:成功时返回验证码,格式为：{“smsCode”:”123456“}、其他情况null
 description:错误信息，成功时为null,出错原因需要给用户提示时有值，其余情况为null
 */
-(void)getCheckCode:(NSString *)phone type:(int) type completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString * description))callback
{
    NSLog(@"%@,getCheckCode entered.phone is %@,type is %d",SyncManager_TAG,phone,type);
    NSString *description=NULL;
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            description=NO_NET_WORK_INFO;
        }
        callback(FAIL,NULL,description);
        return;
    }
    if(phone==NULL||[phone length]!=11)
    {
        NSLog(@"%@,getCheckCode,phone is null or ilegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/auth/requestSmsCode.json",protol,hostName];
    NSString *ts=[Tooler getTS];
    NSString *sign=[Tooler hashByHmac:appsecret data:[phone stringByAppendingString:ts]];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:appkey forKey:@"appKey"];
    [param setValue:phone forKey:@"phoneNum"];
    [param setValue:ts forKey:@"ts"];
    [param setValue:sign forKey:@"sign"];
    [param setValue:[NSString stringWithFormat:@"%d",type] forKey:@"type"];
    [param setValue:@"1" forKey:@"product"];
     NSLog(@"%@,getCheckCode,url is %@",SyncManager_TAG,urtStr);
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        
        if(resdict==NULL||([resdict count]==0))
        {
            NSLog(@"%@,getCheckCode,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSInteger ret=[[resdict valueForKey:@"success"] integerValue];
        
        if(ret==1)
        {
            NSString *smsCode=[resdict valueForKey:@"smsCode"];
            NSLog(@"%@,getCheckCode,sucess smsCode is %@",SyncManager_TAG,smsCode);
            NSMutableDictionary *retV=[[NSMutableDictionary alloc] init];
            [retV setValue:smsCode forKey:@"smsCode"];
            callback(SUCESS,retV,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getCheckCode,fail errorCode is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];

    
}

/*
 手机请求确认SMS验证码:ok
 参数:
 phone:11位电话号码，code:用户输入的验证码、callback:请求返回时的回调函数
 返回值:
 result,表示请求结果，SUCESS:请求成功、FAIL:请求失败
 retValue:null
 description:错误信息 or null

 */
-(void)verifySmsCode:(NSString *)phone smsCode:(NSString *)code completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback

{
    NSLog(@"%@,verifySmsCode entered. phone is %@,code is %@",SyncManager_TAG,phone,code);
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    if(phone==NULL||[phone length]!=11||code==NULL)
    {
        NSLog(@"%@,verifySmsCode, parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/auth/verifySmsCode.json",protol,hostName];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:phone forKey:@"phoneNum"];
    [param setValue:code forKey:@"smsCode"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {

        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,verifySmsCode,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSInteger ret=[[resdict valueForKey:@"success"] integerValue];
        if(ret==1)
        {
            NSLog(@"%@,verifySmsCode, success.",SyncManager_TAG);
            callback(SUCESS,NULL,NULL);
            
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,verifySmsCode, fail error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];

}
/*
 注册手机:ok
 流程是：先调用云端API进行注册手机，返回成功把取到的用户信息插入数据库中
 参数：
 phone：电话号码、pass：密码、callback回调函数
 返回值：
 result,表示请求结果，SUCESS:请求成功、FAIL:请求失败
 retValue:null
 description:错误信息  or null
 */
-(void)registerPhone:(NSString *)phone pass:(NSString *)pass nickname:(NSString *)nickname completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,registerPhone entered. phone is %@,pass is %@,nickname is %@.",SyncManager_TAG,phone,pass,nickname);
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    if(phone==NULL||[phone length]!=11||pass==NULL||[pass length]<=0||nickname==NULL||[nickname length]<=0)
    {
        NSLog(@"%@,registerPhone, parameters are illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/auth/registerPhone.json",protol,hostName];
    NSString *hwVer=[Tooler getMachine];
    NSString *fwVer=[Tooler getSystemVersion];
    NSString *fullName=phone;
    NSString *ts=[Tooler getTS];
    NSString *sign=[Tooler hashByHmac:appsecret data:[[appkey stringByAppendingString:phone] stringByAppendingString:ts] ];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:appkey forKey:@"appKey"];
    [param setValue:phone forKey:@"phoneNum"];
    [param setValue:hwVer forKey:@"hwVer"];
    [param setValue:fwVer forKey:@"fwVer"];
    [param setValue:fullName forKey:@"account"];
    [param setValue:pass forKey:@"password"];
    [param setValue:ts forKey:@"ts"];
    [param setValue:sign forKey:@"sign"];
    [param setValue:nickname forKey:@"nickName"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,registerPhone,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSInteger ret=[[resdict valueForKey:@"success"] integerValue];
        if(ret==1)
        {
            NSString *uid=[resdict valueForKey:@"uid"];
            NSString *timeStamp=[resdict valueForKey:@"ts"];
            NSLog(@"%@,registerPhone,sucess uid is %@",SyncManager_TAG,uid);
            User *user=[User sharedSingleton];
            user.uid=uid;
            user.createTime=timeStamp;
            user.account=phone;
            user.password=pass;
            user.is_active=1;
            user.type=1;
            user.nickName=nickname;
            //返回的用户信息存入数据库
            [self.theManager registerUser:user];
            
             callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,registerPhone, fail error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
        
    }];
    
}
/*
 手机登录:ok
 参数:
 phone:11位电话号码，pass:密码、callback:请求返回时的回调函数
 返回值:
 result,表示请求结果，SUCESS:验证成功、FAIL:请求失败
 retValue:NULL
 description:出错信息 or null
 */
-(void)loginPhone:(NSString *)phone pass:(NSString *)pass completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,loginPhone entered. phone is %@,pass is %@",SyncManager_TAG,phone,pass);
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    if(phone==NULL||[phone length]!=11||pass==NULL)
    {
        NSLog(@"%@,loginPhone,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
   
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/auth/loginPhone.json",protol,hostName];
    NSString *fwVer=[Tooler getSystemVersion];
    NSString *ts=[Tooler getTS];
    NSString *sign=[Tooler hashByHmac:appsecret data:[[appkey stringByAppendingString:phone] stringByAppendingString:ts]];
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    NSString *deviceToken=NULL;
    if(mydelegate.iosdeviceToken==NULL)
    {
    deviceToken=@"28a5518e2712b678a2c8ce751b5dc2a3855ffc2290337caff613afde76b14001";
    }
    else
    {
        deviceToken=[mydelegate.iosdeviceToken substringWithRange:NSMakeRange(1,mydelegate.iosdeviceToken.length-2)];
    }
    NSString *iosToken=mydelegate.iosToken;
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:appkey forKey:@"appKey"];
    [param setValue:phone forKey:@"account"];
    [param setValue:fwVer forKey:@"fwVer"];
    [param setValue:ts forKey:@"ts"];
    [param setValue:sign forKey:@"sign"];
    [param setValue:pass forKey:@"password"];
    [param setValue:@"1" forKey:@"phoneOsType"];//记得修改 ，1sos
    [param setValue:deviceToken forKey:@"deviceToken"];
    [param setValue:iosToken forKey:@"token"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
          if(resdict==NULL||[resdict count]==0)
          {
            NSLog(@"%@,loginPhone,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
          }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret integerValue]==1)
        {
            //登录成功，更改状态
            NSString *accessToken=[resdict valueForKey:@"accessToken"];
            NSString *refreshToken=[resdict valueForKey:@"refreshToken"];
            NSString *uid=[resdict valueForKey:@"uid"];
            NSString *create_time=[resdict valueForKey:@"ts"];
            User *user=[User sharedSingleton];
            if(user==NULL)
            {
                NSLog(@"%@,loginPhone,user is null",SyncManager_TAG);
                callback(FAIL,NULL,NULL);
                return;
            }

            user.uid=[NSString stringWithFormat:@"%@",uid];
            user.account=phone;
            user.password=pass;
            user.accessToken=accessToken;
            user.refreshToken=refreshToken;
            user.is_active=1;
            user.createTime=create_time;
            user.type=1;
            //更改数据库状态,但是可能会有这样一种情况：即登录的用户在数据库中不存在
            //所以，如果用户信息存在数据库中更新，不存在插入
            [self.theManager updateUserInfo:user];
            [self.theManager logoutOtherAccounts:user];
            callback(SUCESS,NULL,NULL);
            
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,loginPhone, fail error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
}

/*
  用户忘记密码: ok
 参数：
 phoneNum:用户注册的手机号码、password:用户设置的新密码、callback回调函数
 返回值：
 result:success成功、fail失败
 retValue:NULL
 description:出错原因 or NULL
 */
-(void)resetPwd:(NSString *)phoneNum password:(NSString *)password smsCode:(NSString *)smsCode completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,resetPwd enteres. phoneNum is %@,password is %@,smsCode is %@.",SyncManager_TAG,phoneNum,password,smsCode);
    if(callback==NULL)
    {
        NSLog(@"%@,resetPwd,callback is null",SyncManager_TAG);
        return;
    }
    if(phoneNum==NULL||[phoneNum length]!=11||password==NULL||[password length]<=0||smsCode==NULL||[smsCode length]<=0)
    {
        NSLog(@"%@,resetPwd,parameters are illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/auth/resetPwd.json",protol,hostName];
    NSString *ts=[Tooler getTS];
    NSString *sign=[Tooler hashByHmac:appsecret data:[[appkey stringByAppendingString:phoneNum] stringByAppendingString:ts]];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:password forKey:@"password"];
    [param setValue:phoneNum forKey:@"account"];
    [param setValue:appkey forKey:@"appKey"];
    [param setValue:ts forKey:@"ts"];
    [param setValue:sign forKey:@"sign"];
    [param setValue:smsCode forKey:@"smscode"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,resetPwd,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret integerValue]==1)
        {
            NSLog(@"%@,resetPwd,sucess",SyncManager_TAG);
            //本地数据库修改密码,这个可以不要
            [self.theManager resetPwd:phoneNum password:password];
            callback(SUCESS,NULL,NULL);
            return;
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,resetPwd fail, error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
        
    }];
}
/*
 手机申请绑定手表：OK
 参数：
 deviceUid绑定手表的uid,bindCode手表的绑定码,alias管理员别名，比如爸爸，妈妈等
 返回值：
 result 请求结果，sucess成功，fail失败
 retValue:请求失败时null；请求成功时、｛role:1｝--绑定成功为主管理员、｛role：2--副管理员，等待主管理员确认
 description:出错原因 or NULL

 */


-(void)bindDevice:(NSString *)deviceUid bindCode:(NSString *)bindCode   alias:(NSString *)alias completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback{
    NSLog(@"%@,bindDevice entered. deviceUid is %@,bindCode is %@,alias is %@.",SyncManager_TAG,deviceUid,bindCode,alias);
    if(callback==NULL)
    {
        NSLog(@"%@,bindDevice,callback is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    if(deviceUid==NULL||bindCode==NULL||alias==NULL)
    {
        NSLog(@"%@,bindDevice,parameters are illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }

    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/auth/bindDevice.json",protol,hostName];
    User *user=[User sharedSingleton];
    NSString *uid=user.uid;
    if(uid==NULL||!([uid integerValue]>0))
    {
        NSLog(@"%@,bindWatch,uid or atoken is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *ts=[Tooler getTS];
    NSString *sign=[Tooler hashByHmac:appsecret data:[[[NSString stringWithFormat:@"%@",uid] stringByAppendingString: appkey] stringByAppendingString:ts]];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:deviceUid forKey:@"deviceUid"];
    [param setValue:bindCode forKey:@"bindCode"];
    [param setValue:ts forKey:@"ts"];
    [param setValue:sign forKey:@"sign"];
    [param setValue:appkey forKey:@"appKey"];
    [param setValue:alias forKey:@"alias"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,bindWatch,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret integerValue]==1)
        {
            //更新本地数据库
            NSMutableDictionary *retValue=[[NSMutableDictionary alloc] init];
            NSString *groupId=[resdict valueForKey:@"groupId"];
            Watch *watch=[[Watch alloc] init];
            if(groupId!=NULL&&[groupId integerValue]>0)//主管理员
            {
                //更新手表信息
                if(watch!=NULL)
                {
                    watch.deviceUid=deviceUid;
                    watch.is_active=1;
                    watch.groupId=groupId;
                    watch.accountId=uid;
                    watch.role=ADMIN;
                    [self.theManager addWatch:watch];
                }
                //更新主管理员信息和绑定信息
                Manager *AdminManager=[[Manager alloc] init];
                if(AdminManager!=NULL)
                {
                    AdminManager.user_id=uid;
                    AdminManager.name=alias;
                    AdminManager.phone=user.account;
                    AdminManager.type=ADMIN;
                    AdminManager.groupId=[groupId intValue];
                    AdminManager.deviceUid=deviceUid;
                    AdminManager.accountId=uid;
                    AdminManager.nickName=user.nickName;
                    AdminManager.alias=alias;
                    [self.theManager addManager:AdminManager];
                }
                //群组新方案策略修改,群组里所有副管理员默认称为新手表的副管理员1230
                NSArray *groupManagers=[self.theManager getDiffGroupManagers:groupId accountId:user.uid];
                if(groupManagers!=NULL&&[groupManagers count]>0)
                {
                    NSMutableArray *managerLists=[[NSMutableArray alloc] init];
                    for(int i=0;i<[groupManagers count];i++)
                    {
                        Manager *manager=[groupManagers objectAtIndex:i];
                        if(manager==NULL||manager.user_id==NULL)
                            continue;
                        manager.name=alias;//所有副管理员关系都一样
                        manager.type=VICE_ADMIN;
                        manager.groupId=[groupId intValue];
                        manager.deviceUid=deviceUid;
                        manager.accountId=uid;
                        manager.alias=alias;
                        manager.action=NULL;
                        [managerLists addObject:manager];
                        manager=NULL;
                    }
                    if(managerLists!=NULL&&[managerLists count]>0)
                        [self.theManager updateManagers:managerLists];

                }

                [retValue setValue:[NSString stringWithFormat:@"%d",ADMIN] forKey:@"role"];
                [retValue setValue:groupId forKey:@"groupId"];
            }
            else if(groupId!=NULL&&[groupId integerValue]==0)// 副管理员,需要等待主管理员确认
            {
                 [retValue setValue:[NSString stringWithFormat:@"%d",VICE_ADMIN] forKey:@"role"];
                 [retValue setValue:@"0" forKey:@"groupId"];

            }
            
            callback(SUCESS,retValue,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,bindDevice fail, error code is %@.",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
    param=NULL;
}

/*
 主管理员确认绑定：修改
 参数：
 deviceUid绑定的手表的uid viceAdminUid:副管理员的uid result:1同意绑定 0拒绝绑定
 返回值：
 result: success成功、fail失败
 retValue:NULL
 description:出错信息 or  null
 
 */
-(void)bindConfirm:(NSString *)deviceUid viceAdminUid:(NSString *) viceAdminUid nickName:(NSString *)nickName result:(BOOL) result  randomCode:(NSString *)randomCode alias:(NSString *)alias completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,bindConfirm entered.deviceUid is %@, viceAdminUid is %@,result is %d,randomCode is %@,alias is %@.",SyncManager_TAG,deviceUid,viceAdminUid,result,randomCode,alias);
    if(deviceUid==NULL||!(deviceUid>0)||viceAdminUid==NULL||!(viceAdminUid>0)||randomCode==NULL||alias==NULL)
    {
        NSLog(@"%@,bindConfirm,parameters are illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/auth/bindConfirm.json",protol,hostName];
    User *user=[User sharedSingleton];
    NSString *uid=user.uid;
    if(uid==NULL||!([uid integerValue]>0))
    {
        NSLog(@"%@,bindConfirm,uid  is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *ts=[Tooler getTS];
    NSString *sign=[Tooler hashByHmac:appsecret data:[[[NSString stringWithFormat:@"%@",uid] stringByAppendingString:appkey] stringByAppendingString:ts]];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:deviceUid forKey:@"deviceUid"];
    [param setValue:sign forKey:@"sign"];
    [param setValue:ts forKey:@"ts"];
    [param setValue:viceAdminUid forKey:@"viceAdminUid"];
    [param setValue:[NSString stringWithFormat:@"%d",result] forKey:@"result"];
    [param setValue:appkey forKey:@"appKey"];
    [param setValue:randomCode forKey:@"randomCode"];
    [param setValue:alias forKey:@"alias"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,bindConfirm,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret integerValue]==1)
        {
            NSLog(@"%@,bindConfirm,success",SyncManager_TAG);
            callback(SUCESS,NULL,NULL);
            /*
            if(result)
            {
                //主管理员同意副管理员绑定请求，更新数据库
                //群组新方案策略修改,该副管理员默认称为群组所有手表的副管理员1230
                
                Watch *watch=[self.theManager getWatch:deviceUid];
                if(watch==NULL||watch.groupId==NULL)
                    return;
                NSArray *groupWatchs=[self.theManager getGroupWatchList:[watch.groupId intValue]];
                if(groupWatchs==NULL||[groupWatchs count]==0)
                    return;
                NSMutableArray *managerLists=[[NSMutableArray alloc] init];
                for(int i=0;i<[groupWatchs count];i++)
                {
                    
                    Watch *theWatch=[groupWatchs objectAtIndex:i];
                    if(theWatch==NULL)
                        return;
                    Manager *manager=[[Manager alloc] init];
                    if(manager==NULL)
                        return;
                    manager.name=alias;
                    manager.type=VICE_ADMIN;
                    manager.groupId=[watch.groupId intValue];
                    manager.deviceUid=theWatch.deviceUid;
                    manager.accountId=uid;
                    manager.alias=alias;
                    manager.action=NULL;
                    manager.user_id=viceAdminUid;
                    manager.nickName=nickName;
                    [managerLists addObject:manager];
                    manager=NULL;
                }
                if(managerLists!=NULL&&[managerLists count]>0)
                    [self.theManager updateManagers:managerLists];
            return;
            }
             */
        }
        else if(ret!=NULL&&[ret integerValue]==0)
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,bindConfirm,fail, error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
    
}

/*
 解除手表绑定关系：OK
 
 */
-(void) unbindDevice:(Watch *)watch  completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,unbindDevice entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,unbindDevice,callback is null",SyncManager_TAG);
        return;
    }
    if(watch==NULL||watch.deviceUid==NULL||watch.groupId==NULL)
    {
        NSLog(@"%@,unbindDevice,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/auth/unbindDevice.json",protol,hostName];
    User *user=[User sharedSingleton];
    NSString *uid=user.uid;
    NSString *ts=[Tooler getTS];
    NSString *sign=[Tooler hashByHmac:appsecret data:[[[NSString stringWithFormat:@"%@",uid] stringByAppendingString:appkey] stringByAppendingString:ts]];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:watch.deviceUid forKey:@"deviceUid"];
    [param setValue:appkey forKey:@"appKey"];
    [param setValue:ts forKey:@"ts"];
    [param setValue:sign forKey:@"sign"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,unbindDevice,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,unbindDevice,success",SyncManager_TAG);
            //解除绑定成功，更新本地数据库，手表所有相关数据都需要删除
            //[self.theManager unbindDevice:deviceUid uid:uid accountId:uid];
            if(watch.role==ADMIN)
            {
                [self.theManager adminUnbindDevice:watch.deviceUid groupId:watch.groupId accountId:uid];
            }
            else if(watch.role==VICE_ADMIN)
            {
                [self.theManager viceAdminUnbindDevice:uid groupId:watch.groupId accountId:uid];
            }

            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,unbindDevice,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
    
}

/*
 主管理员删除副管理员：OK
 
 
 */
-(void)deleteViceAdmin:(NSString *)deviceUid viceAdminUid:(NSString *)viceAdminUid  completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,deleteViceAdmin entered. deviceUid is %@, viceAdminUid is %@",SyncManager_TAG,deviceUid,viceAdminUid);
    if(callback==NULL)
    {
        NSLog(@"%@,deleteViceAdmin,callback is null",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/auth/deleteViceAdmin.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,deleteViceAdmin,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *ts=[Tooler getTS];
    NSString *sign=[Tooler hashByHmac:appsecret data:[[[NSString stringWithFormat:@"%@",uid] stringByAppendingString:appkey] stringByAppendingString:ts]];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:viceAdminUid forKey:@"viceAdminUid"];
    [param setValue:deviceUid forKey:@"deviceUid"];
    [param setValue:appkey forKey:@"appKey"];
    [param setValue:ts forKey:@"ts"];
    [param setValue:sign forKey:@"sign"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,deleteViceAdmin,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            
            //从本地数据库把这个副管理员删除
            Manager *manager=[[Manager alloc] init];
            manager.deviceUid=deviceUid;
            manager.user_id=viceAdminUid;
            manager.accountId=uid;
            [self.theManager deleteManager:manager];
            //回调函数，通知UI
            callback(SUCESS,FAIL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,deleteViceAdmin,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
}
-(void)inviteViceAdmin:(NSString *)deviceUid vaaccount:(NSString *)vaaccount completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,inviteViceAdmin entered. deviceUid is %@, vaaccount is %@",SyncManager_TAG,deviceUid,vaaccount);
    if(callback==NULL||deviceUid==NULL||vaaccount==NULL)
    {
        NSLog(@"%@,inviteViceAdmin,callback is null",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/auth/inviteViceAdmin.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,inviteViceAdmin,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *ts=[Tooler getTS];
    NSString *sign=[Tooler hashByHmac:appsecret data:[[[NSString stringWithFormat:@"%@",uid] stringByAppendingString:appkey] stringByAppendingString:ts]];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:deviceUid forKey:@"deviceUid"];
    [param setValue:vaaccount forKey:@"vaaccount"];
    [param setValue:appkey forKey:@"appKey"];
    [param setValue:ts forKey:@"ts"];
    [param setValue:sign forKey:@"sign"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,inviteViceAdmin,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSString *nickName=[resdict valueForKey:@"nickName"];
            NSString *uid=[resdict valueForKey:@"uid"];
            NSMutableDictionary *retValue=[[NSMutableDictionary alloc] init];
            [retValue setValue:nickName forKey:@"nickName"];
            [retValue setValue:@"1" forKey:@"type"];
            [retValue setValue:uid forKey:@"uid"];
            //回调函数，通知UI
            callback(SUCESS,retValue,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,inviteViceAdmin,fail,error code is %@",SyncManager_TAG,errorCode);
            if(errorCode!=NULL&&[errorCode intValue]==USER_UNEXIST)
            {
                NSMutableDictionary *retValue=[[NSMutableDictionary alloc] init];
                [retValue setValue:@"2" forKey:@"type"];
                callback(SUCESS,retValue,NULL);
            }
            else
              callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];

}



/******************************************************
 app上传下载数据相关接口
 ******************************************************/
/*
 获取手表的所有管理员：ok
 
 */
-(void)getBoundUsers:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getBoundUsers entered. deviceUid is %@",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,getBoundUsers,callback is null",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getBoundUsers,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *ts=[self.theManager getManagerTS:deviceUid accountId:uid];
    if([ts isEqualToString:@"(null)"]||ts==NULL||[ts isEqualToString:@""])
    {
        ts=@"null";
        AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
        if(mydelegate!=NULL)
            mydelegate.isReceiveBindRelationChange=NO;
    }
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"ts\":%@}",deviceUid,ts];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getBoundUsers" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getBoundUsers,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getBoundUsers success.",SyncManager_TAG);
            //解析取到的管理员数据
            NSMutableArray *managerList=[[NSMutableArray alloc] init];
            NSArray *retData=[resdict valueForKey:@"users"];
            NSString *groupId=[resdict valueForKey:@"groupId"];
            NSString *ts=[resdict valueForKey:@"ts"];
            for(int i=0;i<[retData count];i++)
            {
                NSDictionary *managerInfo=[retData objectAtIndex:i];
                if(managerInfo==NULL||[managerInfo valueForKey:@"uid"]==NULL)
                {
                    NSLog(@"%@,getBoundDevices,watchInfo is null,i is %d",SyncManager_TAG,i);
                    continue;
                }
                Manager *manager=[[Manager alloc] init];
                if(manager!=NULL)
                {
                    manager.user_id=[managerInfo valueForKey:@"uid"];
                    manager.phone=[managerInfo valueForKey:@"phoneNum"];
                    manager.alias=[managerInfo valueForKey:@"alias"];
                    manager.photoHash=[managerInfo valueForKey:@"photoHash"];
                    manager.action=[managerInfo valueForKey:@"action"];
                    manager.deviceUid=deviceUid;
                    manager.accountId=uid;
                    manager.type=[Tooler getManagerType:[[managerInfo valueForKey:@"role"] intValue]];
                    manager.groupId=[groupId intValue];
                    manager.birth=[managerInfo valueForKey:@"birthday"];
                    manager.nickName=[managerInfo valueForKey:@"nickName"];
                    manager.update_time=ts;
                    manager.isSos=[[managerInfo valueForKey:@"isSos"] intValue];
                    manager.pic_url=[managerInfo valueForKey:@"url"];
                    [managerList addObject:manager];
                    manager=NULL;
                }

            }
            //管理人员信息，更新到本地数据库
            NSLog(@"%@,getBoundDevices,manager count is %d",DATAMANAGER_TAG,(int)[managerList count]);
            if([managerList count]>0)
            {
                [self.theManager updateManagers:managerList];
            }
            //如果头像发生变化，取新的头像
            [self getManagerPhotos:managerList deviceUid:deviceUid];
            //通知UI
            callback(SUCESS,NULL,NULL);
            
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getBoundUsers,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
}
-(void)getManagerPhotos:(NSMutableArray *)newPhotoList deviceUid:(NSString *)deviceUid
{
    NSLog(@"%@,getManagerPhotos entered,deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(newPhotoList==NULL||[newPhotoList count]==0||deviceUid==NULL||!([deviceUid intValue]>0))
    {
        NSLog(@"%@,getManagerPhotos,newPhotoList is null.",SyncManager_TAG);
        return;
    }
    //读取已有photoHash
    NSMutableDictionary *oldPhotoList=[self.theManager getManagerPhotoHash:deviceUid];
    for(int i=0;i<[newPhotoList count];i++)
    {
        Manager *manager=[newPhotoList objectAtIndex:i];
        if(manager==NULL||manager.photoHash==NULL||[manager.photoHash isEqualToString:@"(null)"])
        {
            NSLog(@"%@,getManagerPhotos,watch is null.",DATAMANAGER_TAG);
            continue;
        }
        NSString *newPhotoHash=manager.photoHash;
        NSString *managerId=manager.user_id;
        NSString *oldPhotoHash=NULL;
        if(oldPhotoList!=NULL&&[oldPhotoList count]>0)
        {
            oldPhotoHash=[oldPhotoList valueForKey:[NSString stringWithFormat:@"%@",managerId]];
        }
        if(oldPhotoHash==NULL||![oldPhotoHash isEqualToString:newPhotoHash])
        {
            //取新头像
            @try {
			
                dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                if(queue==NULL)
                {
                    NSLog(@"%@,getManagerPhotos,queue is null",DATAMANAGER_TAG);
                    return;
                }
                dispatch_async(queue, ^{
                    if(manager.pic_url!=NULL&&![manager.pic_url isEqualToString:@"(null)"]&&![manager.pic_url isEqualToString:@""])
                    {
                       //[self getPhotoByUrl:newPhotoHash url:manager.pic_url theUid:managerId type:MANAGER];
                        [self getPhoto:newPhotoHash theUid:managerId type:MANAGER];
                    }
                    else
                    {
                        [self getPhoto:newPhotoHash theUid:managerId type:MANAGER];
                    }

                    
                });
                
            }
            @catch (NSException *exception) {
                NSLog(@"%@,getManagerPhotos,exception is %@",DATAMANAGER_TAG,[exception reason]);
            }
            @finally {
                
            }
            
            
            
        }
    }
}
/*
 获取APP绑定的所有手表：OK
 
 */
-(void)getBoundDevices:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getBoundDevices entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,getBoundDevices,callback is null",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL||!([user.uid intValue]>0))
    {
        NSLog(@"%@,getBoundDevices,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *ts=[self.theManager getWatchTS:uid];
    if([ts isEqualToString:@"(null)"]||ts==NULL||[ts isEqualToString:@""])
    {
        ts=@"null";
    }
    NSString *data=[NSString stringWithFormat:@"{\"ts\":%@}",ts];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getBoundDevices" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getBoundDevices,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getBoundDevices success.",SyncManager_TAG);
            //把获取到的设备信息解析
            NSMutableArray *watchList=[[NSMutableArray alloc] init];
            NSArray *retData=[resdict valueForKey:@"users"];
            NSString *updateTime=[resdict valueForKey:@"ts"];
            for(int i=0;i<[retData count];i++)
            {
                NSDictionary *watchInfo=[retData objectAtIndex:i];
                if(watchInfo==NULL)
                {
                    NSLog(@"%@,getBoundDevices,watchInfo is null,i is %d",SyncManager_TAG,i);
                    continue;
                }
                Watch *watch=[[Watch alloc] init];
                if(watch!=NULL)
                {
                    watch.deviceUid=[watchInfo valueForKey:@"uid"];
                    watch.sim=[watchInfo valueForKey:@"phoneNum"];
                    watch.nickname=[watchInfo valueForKey:@"nickName"];
                    watch.gender=[[watchInfo valueForKey:@"sex"] intValue];
                    watch.birth=[watchInfo valueForKey:@"birthday"];
                    watch.weight=[[watchInfo valueForKey:@"weight"] floatValue];
                    watch.height=[[watchInfo valueForKey:@"height"] floatValue];
                    watch.mac=[watchInfo valueForKey:@"mac"];
                    watch.imei=[watchInfo valueForKey:@"imei"];
                    watch.photoHash=[watchInfo valueForKey:@"photoHash"];
                    watch.action=[watchInfo valueForKey:@"action"];
                    watch.update_time=updateTime;
                    watch.is_active=1;
                    watch.className=[watchInfo valueForKey:@"grade"];
                    watch.accountId=uid;
                    watch.groupId=[watchInfo valueForKey:@"groupId"];
                    watch.role=[[watchInfo valueForKey:@"role"] intValue];
                    watch.pic_url=[watchInfo valueForKey:@"url"];
                    [watchList addObject:watch];
                    watch=NULL;
                }

            }
            
            //更新本地数据库
            [self.theManager updateWatches:watchList];
            
            //如果头像发生变化，取新的头像
            [self getWatchPhotos:watchList];
            
            //通知UI
            NSMutableDictionary *retValue=[[NSMutableDictionary alloc] init];
            if([watchList count]>0)
                [retValue setValue:[NSString stringWithFormat:@"%d",(int)[watchList count]] forKey:@"watchCount"];
            else
            {
                if([ts isEqualToString:@"null"])
                    [retValue setValue:@"-1" forKey:@"watchCount"];
                else
                    [retValue setValue:@"0" forKey:@"watchCount"];
            }
            callback(SUCESS,retValue,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getBoundDevices,fail,error code is %@.",SyncManager_TAG,errorCode);
            if([errorCode intValue]==USER_BIND_DEVICE_NULL)
            {
                NSMutableDictionary *retValue=[[NSMutableDictionary alloc] init];
                [retValue setValue:@"-1" forKey:@"watchCount"];
                callback(SUCESS,retValue,USER_BIND_DEVICE_NULL_INFO);
            }
            else
            {
                callback(FAIL,NULL,[self getErrorInfo:errorCode]);
            }
            
        }
    }];
}
-(void)getWatchPhotos:(NSMutableArray *)newPhotoList
{
    NSLog(@"%@,getWatchPhotos entered.",SyncManager_TAG);
    if(newPhotoList==NULL||[newPhotoList count]==0)
    {
        NSLog(@"%@,getWatchPhotod,newPhotoList is null.",SyncManager_TAG);
        return;
    }
    //读取已有photoHash
    NSMutableDictionary *oldPhotoList=[self.theManager  getWatchPhotoHash];
    for(int i=0;i<[newPhotoList count];i++)
    {
        Watch *watch=[newPhotoList objectAtIndex:i];
        if(watch==NULL||watch.photoHash==NULL||[watch.photoHash isEqualToString:@"(null)"])
        {
            NSLog(@"%@,getWatchPhotos,watch is null.",DATAMANAGER_TAG);
            continue;
        }
        NSString *newPhotoHash=watch.photoHash;
        NSString *deviceUid=watch.deviceUid;
        NSString *oldPhotoHash=NULL;
        if(oldPhotoList!=NULL&&[oldPhotoList count]>0)
        {
            oldPhotoHash=[oldPhotoList valueForKey:[NSString stringWithFormat:@"%@",deviceUid]];
        }
        if(oldPhotoHash==NULL||![oldPhotoHash isEqualToString:newPhotoHash])
        {
            //取新头像
            @try {
			
                dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                if(queue==NULL)
                {
                    NSLog(@"%@,getWatchPhotos,queue is null",DATAMANAGER_TAG);
                    return;
                }
                dispatch_async(queue, ^{
                    if(watch.pic_url!=NULL&&![watch.pic_url isEqualToString:@"(null)"]&&![watch.pic_url isEqualToString:@""])
                    {

                        //[self getPhotoByUrl:newPhotoHash url:watch.pic_url theUid:deviceUid type:WATCH];
                        [self getPhoto:newPhotoHash theUid:deviceUid type:WATCH];
                    }
                    else
                    {
                        [self getPhoto:newPhotoHash theUid:deviceUid type:WATCH];
                    }

                    });
                
            }
            @catch (NSException *exception) {
                NSLog(@"%@,getWatchPhotos,exception is %@",DATAMANAGER_TAG,[exception reason]);
            }
            @finally {
                
            }

            
            
        }
    }
}
-(void)getPhotoByUrl:(NSString *)photoHash url:(NSString *)url theUid:(NSString *)theUid type:(Type)type
{
    NSLog(@"%@,getPhotoByUrl entered,url is %@.",SyncManager_TAG,url);
    if(url==NULL||[url isEqualToString:@"(null)"]||[url length]==0)
    {
        NSLog(@"%@,getPhotoByUrl,url is illegal.",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        return;
    }
    /*
            dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            if(queue==NULL)
            {
                NSLog(@"%@,getPhotoByUrl,queue is null",DATAMANAGER_TAG);
                return;
            }*/
            //dispatch_async(queue, ^{
                //下载头像
                NSString *directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/headimg"];
                if(![Tooler isDirectoryExist:directoryPath])
                {
                    return;
                }
                NSString *ts=[Tooler getTS];
                NSString *filePath=[directoryPath stringByAppendingString:[NSString stringWithFormat:@"/image%@%@.jpg",theUid,ts]];
                BOOL is_downLoad=[self.theRequeseter downLoadFile:url filePath:filePath];
                if(is_downLoad)
                {
                    NSString *fileUrl=[NSString stringWithFormat:@"/headimg/image%@%@.jpg",theUid,ts];
                    //保存到数据库
                    if(type==WATCH)
                    {
                        [self.theManager updateWatchPhoto:theUid filePath:fileUrl photoHash:photoHash];
                        [[NSNotificationCenter defaultCenter] postNotificationName:WATCHPHOTOUPDATE object:nil  userInfo:nil];
                        
                    }
                    else if(type==MANAGER)
                    {
                        [self.theManager updateManagerPhoto:theUid filePath:fileUrl photoHash:photoHash];
                        [[NSNotificationCenter defaultCenter] postNotificationName:MANAGERPHOTOUPDATE object:nil  userInfo:nil];
                        
                    }
                    else if(type==PHONECONTACT)
                    {
                        [self.theManager updateContactPhoto:theUid filePath:fileUrl photoHash:photoHash];
                         [[NSNotificationCenter defaultCenter] postNotificationName:ContactPHOTOUPDATE object:nil  userInfo:nil];
                        
                    }
                    else if(type==USER)
                    {
                        User *user=[User sharedSingleton];
                        if(user==NULL)
                            return;
                        user.pic_url=fileUrl;
                        user.photoHash=photoHash;
                        [self.theManager updateUser:user];
                    }
                    
                }
                else
                {
                    //下载失败，保存hash到数据库
                    if(type==WATCH)
                    {
                        [self.theManager updateWatchPhoto:theUid filePath:NULL photoHash:photoHash];
                        
                    }
                    else if(type==MANAGER)
                    {
                        [self.theManager updateManagerPhoto:theUid filePath:NULL photoHash:photoHash];
                        
                    }
                    else if(type==PHONECONTACT)
                    {
                        [self.theManager updateContactPhoto:theUid filePath:NULL photoHash:photoHash];
                        
                    }
                    else if(type==USER)
                    {
                        User *user=[User sharedSingleton];
                        if(user==NULL)
                            return;
                        user.pic_url=NULL;
                        user.photoHash=photoHash;
                        [self.theManager updateUser:user];
                    }
                }
            //});
  
}

-(void)getPhoto:(NSString *)photoHash theUid:(NSString *)theUid type:(Type)type
{
    NSLog(@"%@,getPhoto entered,photoHash is %@.",SyncManager_TAG,photoHash);
    if(photoHash==NULL||[photoHash isEqualToString:@"(null)"]||[photoHash length]==0)
    {
        NSLog(@"%@,getPhoto,photoHash is illegal.",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getPhoto,user is null",SyncManager_TAG);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"fileHash\":\"%@\"}",photoHash];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:data forKey:@"data"];
    [param setValue:@"UserApiImpl.getFileUrl" forKey:@"method"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getPhoto,resdict is null",SyncManager_TAG);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            if(queue==NULL)
            {
                NSLog(@"%@,getManagerPhotos,queue is null",DATAMANAGER_TAG);
                return;
            }
            dispatch_async(queue, ^{
                
            NSString *url=[resdict valueForKey:@"url"];
            if(url==NULL||[url length]<=0)
            {
                NSLog(@"%@,getPhoto,url is null.",DATAMANAGER_TAG);
                return;
            }
            //下载头像
            NSString *directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/headimg"];
            if(![Tooler isDirectoryExist:directoryPath])
            {
                return;
            }
            NSString *ts=[Tooler getTS];
            NSString *filePath=[directoryPath stringByAppendingString:[NSString stringWithFormat:@"/image%@%@.jpg",theUid,ts]];
            BOOL is_downLoad=[self.theRequeseter downLoadFile:url filePath:filePath];
            if(is_downLoad)
            {
                NSString *fileUrl=[NSString stringWithFormat:@"/headimg/image%@%@.jpg",theUid,ts];
                //保存到数据库
                if(type==WATCH)
                {
                    [self.theManager updateWatchPhoto:theUid filePath:fileUrl photoHash:photoHash];
                    [[NSNotificationCenter defaultCenter] postNotificationName:WATCHPHOTOUPDATE object:nil  userInfo:nil];
                    
                }
                else if(type==MANAGER)
                {
                    [self.theManager updateManagerPhoto:theUid filePath:fileUrl photoHash:photoHash];
                    [[NSNotificationCenter defaultCenter] postNotificationName:MANAGERPHOTOUPDATE object:nil  userInfo:nil];
                    
                }
                else if(type==PHONECONTACT)
                {
                    [self.theManager updateContactPhoto:theUid filePath:fileUrl photoHash:photoHash];
                    [[NSNotificationCenter defaultCenter] postNotificationName:ContactPHOTOUPDATE object:nil  userInfo:nil];
                    
                }
                else if(type==USER)
                {
                    User *user=[User sharedSingleton];
                    if(user==NULL)
                        return;
                    user.pic_url=fileUrl;
                    user.photoHash=photoHash;
                    [self.theManager updateUser:user];
                }

            }
            else
            {
                //下载失败，保存hash到数据库
                if(type==WATCH)
                {
                    [self.theManager updateWatchPhoto:theUid filePath:NULL photoHash:photoHash];
                    
                }
                else if(type==MANAGER)
                {
                    [self.theManager updateManagerPhoto:theUid filePath:NULL photoHash:photoHash];
                    
                }
                else if(type==PHONECONTACT)
                {
                    [self.theManager updateContactPhoto:theUid filePath:NULL photoHash:photoHash];
                    
                }
                else if(type==USER)
                {
                    User *user=[User sharedSingleton];
                    if(user==NULL)
                        return;
                    user.pic_url=NULL;
                    user.photoHash=photoHash;
                    [self.theManager updateUser:user];
                }

            }
            });
        }
        
    }];

}
/*
 
 */

/************************************************
联系人相关API
 ************************************************/
/*
 app获取手表所有联系人:ok
 
 */
-(void)getWatchContact:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getWatchContact entered. deviceUid is %@",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,getWatchContact,callback is null",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getWatchContact,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *ts=[self.theManager getContactTS:deviceUid accountId:uid];
    if([ts isEqualToString:@"(null)"]||ts==NULL||[ts isEqualToString:@""])
    {
        ts=@"null";
    }
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"ts\":'%@'}",deviceUid,ts];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"ContactApiImpl.getContacts" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getWatchContact,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getWatchContact success.",SyncManager_TAG);
            //解析取到的联系人数据
            NSMutableArray *contactList=[[NSMutableArray alloc] init];
            NSArray *retData=[resdict valueForKey:@"contactList"];
            NSString *updateTime=[resdict valueForKey:@"ts"];
            for(int i=0;i<[retData count];i++)
            {
                NSDictionary *contactInfo=[retData objectAtIndex:i];
                if(contactInfo==NULL||[contactInfo valueForKey:@"phoneNum"]==NULL)
                {
                    NSLog(@"%@,getWatchContact,contactInfo is null,i is %d",SyncManager_TAG,i);
                    continue;
                }
                Contact *contact=[[Contact alloc] init];
                if(contact!=NULL)
                {
                    contact.user_id=[contactInfo valueForKey:@"id"];
                    contact.phoneNum=[contactInfo valueForKey:@"phoneNum"];
                    contact.contactname=[contactInfo valueForKey:@"alias"];
                    contact.photoHash=[contactInfo valueForKey:@"photoHash"];
                    contact.action=[contactInfo valueForKey:@"action"];
                    contact.deviceUid=deviceUid;
                    contact.accountId=uid;
                    contact.type=[Tooler getContactType:[[contactInfo valueForKey:@"type"] intValue]];
                    contact.update_time=updateTime;
                    contact.photo_url=[contactInfo valueForKey:@"url"];
                    [contactList addObject:contact];
                    contact=NULL;
                    
                }

            }
            
            //更新到本地数据库
            [self.theManager updateContacts:contactList];
            //如果头像发生变化，取新的头像
            [self getContactPhotos:contactList deviceUid:deviceUid];
            //通知UI
            callback(SUCESS,NULL,NULL);
            
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getWatchContact,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
}
-(void)getContactPhotos:(NSMutableArray *)newPhotoList deviceUid:(NSString *)deviceUid
{
    NSLog(@"%@,getContactPhotos entered,deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(newPhotoList==NULL||[newPhotoList count]==0||deviceUid==NULL||!([deviceUid intValue]>0))
    {
        NSLog(@"%@,getContactPhotos,newPhotoList is null.",SyncManager_TAG);
        return;
    }
    //读取已有photoHash
    NSMutableDictionary *oldPhotoList=[self.theManager getContactPhotoHash:deviceUid];
    for(int i=0;i<[newPhotoList count];i++)
    {
        Contact *contact=[newPhotoList objectAtIndex:i];
        if(contact==NULL||contact.photoHash==NULL||[contact.photoHash isEqualToString:@"(null)"])
        {
            NSLog(@"%@,getContactPhotos,watch is null.",DATAMANAGER_TAG);
            continue;
        }
        NSString *newPhotoHash=contact.photoHash;
        NSString *userId=contact.user_id;
        NSString *oldPhotoHash=NULL;
        if(oldPhotoList!=NULL&&[oldPhotoList count]>0)
        {
            oldPhotoHash=[oldPhotoList valueForKey:[NSString stringWithFormat:@"%@",userId]];
        }
        if(oldPhotoHash==NULL||![oldPhotoHash isEqualToString:newPhotoHash])
        {
            //取新头像
            @try {
			
                dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                if(queue==NULL)
                {
                    NSLog(@"%@,getContactPhotos,queue is null",DATAMANAGER_TAG);
                    return;
                }
                dispatch_async(queue, ^{
                    if(contact.photo_url!=NULL&&![contact.photo_url isEqualToString:@"(null)"]&&![contact.photo_url isEqualToString:@""])
                    {
                        //[self getPhotoByUrl:newPhotoHash url:contact.photo_url theUid:userId type:PHONECONTACT];
                        [self getPhoto:newPhotoHash theUid:userId type:PHONECONTACT];
                    }
                    else
                    {
                        [self getPhoto:newPhotoHash theUid:userId type:PHONECONTACT];
                    }
                });
                
            }
            @catch (NSException *exception) {
                NSLog(@"%@,getContactPhotos,exception is %@",DATAMANAGER_TAG,[exception reason]);
            }
            @finally {
                
            }
            
            
            
        }
    }
}


/*
 app删除手表联系人：ok
 
 */
-(void)deleteContact:(NSString *)deviceUid contactId:(NSString *)contactId completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,deleteContact entered. deviceUid is %@,contactId is %@.",SyncManager_TAG,deviceUid,contactId);
    if(callback==NULL)
    {
        NSLog(@"%@,deleteContact,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0||contactId==NULL||[contactId intValue]<=0)
    {
        NSLog(@"%@,deleteContact,parameters is illegal.",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,deleteContact,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"contact\":{\"id\":%@}}",deviceUid,contactId];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"ContactApiImpl.deleteContact" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,deleteContact,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,deleteContact,result is sucess.",SyncManager_TAG);
            //删除联系人成功，更新到本地数据库
            Contact *contact=[[Contact alloc] init];
            contact.user_id=contactId;
            contact.deviceUid=deviceUid;
            contact.accountId=uid;
            [self.theManager deleteContact:contact];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,deleteContact,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
}
/*
 app给手表添加联系人 ok
 */
-(void)addWatchContact:(Contact *)contact  completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,addWatchContact entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,addWatchContact,callback is null",SyncManager_TAG);
        return;
    }
    //if(contact==NULL||contact.phoneNum==NULL||[contact.phoneNum length]!=11)
    if(contact==NULL||contact.phoneNum==NULL)
    {
        NSLog(@"%@,addWatchContact,parameters is illegal.",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    contact.update_time=[Tooler getTS];
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,addWatchContact,user is null.",DATAMANAGER_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    float psize=[Tooler fileSizeAtPath:contact.photo_url];
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"contact\":{\"alias\":\"%@\",\"phoneNum\":\"%@\",\"photoSize\":%f,\"type\":%d}}",contact.deviceUid,contact.contactname,contact.phoneNum,psize,contact.type];
    
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"ContactApiImpl.addContact" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    NSString *urlStr=[NSString stringWithFormat:@"%@://%@/v1/api/upload.json",protol,hostName];
    NSString *fileName=contact.photoName;
    NSString *filePath=contact.photo_url;
    
    @try {
        
        [self.theRequeseter postFile:urlStr  fileName:fileName filePath:filePath param:param completion:^(NSDictionary *resdict) {
            if(resdict==NULL||[resdict count]==0)
            {
                NSLog(@"%@,addWatchContact,resdict is null",SyncManager_TAG);
                callback(NODATA,NULL,NULL);
                return;
            }
            NSString *ret=[resdict valueForKey:@"success"];
            if(ret!=NULL&&[ret intValue]==1)
            {
                NSLog(@"%@,addWatchContact,result is sucess.",SyncManager_TAG);
                // 新增联系人成功，更新到本地数据库
                contact.accountId=user.uid;
                contact.photoHash=[resdict valueForKey:@"photoHash"];
                contact.user_id=[resdict valueForKey:@"id"];
                contact.type=[Tooler getContactType:contact.type];
                [self.theManager addContact:contact];
                callback(SUCESS,NULL,NULL);
            }
            else
            {
                NSString *errorCode=[resdict valueForKey:@"errorCode"];
                NSLog(@"%@,addWatchContact,fail,error code is %@",SyncManager_TAG,errorCode);
                callback(FAIL,NULL,[self getErrorInfo:errorCode]);
            }
        }];
        
    }
    @catch (NSException *ex) {
        NSLog(@"%@,addWatchContact,exception is %@",SyncManager_TAG,ex.reason);
    }
    @finally {
        
    }
    

}

/*
 app更新手表联系人:ok
 */
-(void)setWatchContact:(Contact *)contact completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,setWatchContact entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,setWatchContact,callback is null",SyncManager_TAG);
        return;
    }
    //if(contact==NULL||contact.phoneNum==NULL||[contact.phoneNum length]!=11)
    if(contact==NULL||contact.phoneNum==NULL)
    {
        NSLog(@"%@,setWatchContact,parameters is illegal.",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    contact.update_time=[Tooler getTS];
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,setWatchContact,user is null.",DATAMANAGER_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    float pszie=[Tooler fileSizeAtPath:contact.photo_url];
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"contact\":{\"id\":%@,\"alias\":\"%@\",\"phoneNum\":%@,\"photoSize\":%f,\"type\":%d}}",contact.deviceUid,contact.user_id,contact.contactname,contact.phoneNum,pszie,contact.type];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"ContactApiImpl.setContact" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    
    NSString *urlStr=[NSString stringWithFormat:@"%@://%@/v1/api/upload.json",protol,hostName];
    
    @try {
        
        [self.theRequeseter postFile:urlStr  fileName:contact.photoName filePath:contact.photo_url  param:param completion:^(NSDictionary *resdict) {
            if(resdict==NULL||[resdict count]==0)
            {
                NSLog(@"%@,setWatchContact,resdict is null",SyncManager_TAG);
                callback(NODATA,NULL,NULL);
                return;
            }
            NSString *ret=[resdict valueForKey:@"success"];
            if(ret!=NULL&&[ret intValue]==1)
            {
                NSLog(@"%@,setWatchContact,result is sucess.",SyncManager_TAG);
                // 更新联系人成功，更新到本地数据库
                contact.accountId=user.uid;
                contact.photoHash=[resdict valueForKey:@"photoHash"];
                contact.type=[Tooler getContactType:contact.type];
                [self.theManager addContact:contact];
                callback(SUCESS,NULL,NULL);
            }
            else
            {
                NSString *errorCode=[resdict valueForKey:@"errorCode"];
                NSLog(@"%@,setWatchContact,fail,error code is %@",SyncManager_TAG,errorCode);
                callback(FAIL,NULL,[self getErrorInfo:errorCode]);
            }

        }];
        
    }
    @catch (NSException *ex) {
        NSLog(@"%@,setWatchContact,exception is %@",SyncManager_TAG,ex.reason);
    }
}
/*********************************************
 用户及手表信息设置相关API
 *********************************************/
/*
 用户更新设置个人信息：ok
 
 */
-(void)setUserInfo:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,setUserInfo entered. ",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,setUserInfo,callback is null",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,setUserInfo,user is null.",DATAMANAGER_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *data=[NSString stringWithFormat:@"{\"birthday\":%@,\"age\":%d,\"email\":\"%@\",\"address\":\"%@\",\"nickName\":\"%@\"}",user.birth,user.age,user.email,user.address,user.nickName];
    
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.setUserInfo" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    
    NSString *urlStr=[NSString stringWithFormat:@"%@://%@/v1/api/upload.json",protol,hostName];
    @try {
        [self.theRequeseter postFile:urlStr  fileName:user.photoName filePath:user.full_url param:param completion:^(NSDictionary *resdict) {
            
            if(resdict==NULL||[resdict count]==0)
            {
                NSLog(@"%@,setUserInfo,resdict is null",SyncManager_TAG);
                callback(NODATA,NULL,NULL);
                return;
            }
            NSString *ret=[resdict valueForKey:@"success"];
            if(ret!=NULL&&[ret intValue]==1)
            //if(1)
            {
                NSLog(@"%@,setUserInfo,result is sucess.",SyncManager_TAG);
                // 设置用户信息成功，更新到本地数据库
                user.photoHash=[resdict valueForKey:@"photoHash"];
                [self.theManager updateUser:user];
                callback(SUCESS,NULL,NULL);
            }
            else
            {
                NSString *errorCode=[resdict valueForKey:@"errorCode"];
                NSLog(@"%@,setUserInfo,fail,error code is %@",SyncManager_TAG,errorCode);
                callback(FAIL,NULL,[self getErrorInfo:errorCode]);
            }

            
        }];
    }
    @catch (NSException *exception) {
        NSLog(@"%@,setUserInfo,exception is %@. ",DATAMANAGER_TAG,exception.reason);
    }
    @finally {
        
    }

}


-(void)setUserInfo1:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,setUserInfo entered. ",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,setUserInfo,callback is null",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,setUserInfo,user is null.",DATAMANAGER_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    if(user.birth==NULL||[user.birth isEqualToString:@"(null)"])
    {
        user.birth=@"0";
    }
    NSString *data=[NSString stringWithFormat:@"{\"birthday\":%@,\"age\":%d,\"email\":\"%@\",\"address\":\"%@\",\"nickName\":\"%@\"}",user.birth,user.age,user.email,user.address,user.nickName];
    
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.setUserInfo" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    
    NSString *urlStr=[NSString stringWithFormat:@"%@://%@/v1/api/upload.json",protol,hostName];
    @try {
        [self.theRequeseter postFile:urlStr  fileName:NULL filePath:NULL param:param completion:^(NSDictionary *resdict) {
            
            if(resdict==NULL||[resdict count]==0)
            {
                NSLog(@"%@,setUserInfo,resdict is null",SyncManager_TAG);
                callback(NODATA,NULL,NULL);
                return;
            }
            NSString *ret=[resdict valueForKey:@"success"];
            if(ret!=NULL&&[ret intValue]==1)
            {
                NSLog(@"%@,setUserInfo,result is sucess.",SyncManager_TAG);
                // 设置用户信息成功，更新到本地数据库
                [self.theManager updateUser:user];
                callback(SUCESS,NULL,NULL);
            }
            else
            {
                NSString *errorCode=[resdict valueForKey:@"errorCode"];
                NSLog(@"%@,setUserInfo,fail,error code is %@",SyncManager_TAG,errorCode);
                callback(FAIL,NULL,[self getErrorInfo:errorCode]);
            }
            
            
        }];
    }
    @catch (NSException *exception) {
        NSLog(@"%@,setUserInfo,exception is %@. ",DATAMANAGER_TAG,exception.reason);
    }
    @finally {
        
    }
    
}

/*
 app用户更新设置手表信息：ok
 */
-(void)setWatchInfo:(Watch *)watch completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,setWatchInfo entered. ",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,setWatchInfo,callback is null",SyncManager_TAG);
        return;
    }
    if(watch==NULL||watch.deviceUid==NULL)
    {
        NSLog(@"%@,setWatchInfo,parameters is illegal.",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,setWatchInfo,user is null.",DATAMANAGER_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *data=NULL;
    if(watch.birth!=NULL&&![watch.birth isEqualToString:@"(null)"])
    {
        data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"nickName\":\"%@\",\"height\":%f,\"weight\":%f,\"age\":%d,\"birthday\":\"%@\",\"grade\":\"%@\",\"sex\":%d,\"phoneNum\":\"%@\"}",watch.deviceUid,watch.nickname,watch.height,watch.weight,watch.age,watch.birth,watch.className,watch.gender,watch.sim];
    }
    else
    {
        data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"nickName\":\"%@\",\"height\":%f,\"weight\":%f,\"age\":%d,\"grade\":\"%@\",\"sex\":%d,\"phoneNum\":\"%@\"}",watch.deviceUid,watch.nickname,watch.height,watch.weight,watch.age,watch.className,watch.gender,watch.sim];
    }
    
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.setWatchInfo" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    
    NSString *urlStr=[NSString stringWithFormat:@"%@://%@/v1/api/upload.json",protol,hostName];
    @try {
        [self.theRequeseter postFile:urlStr   fileName:watch.photoName filePath:watch.pic_url param:param completion:^(NSDictionary *resdict) {
            if(resdict==NULL||[resdict count]==0)
            {
                NSLog(@"%@,setWatchInfo,resdict is null",SyncManager_TAG);
                callback(NODATA,NULL,NULL);
                return;
            }
            NSString *ret=[resdict valueForKey:@"success"];
            if(ret!=NULL&&[ret intValue]==1)
            {
                NSLog(@"%@,setWatchInfo,result is sucess.",SyncManager_TAG);
                // 设置手表信息成功，更新到本地数据库
                watch.photoHash=[resdict valueForKey:@"photoHash"];
                watch.accountId=user.uid;
                [self.theManager addWatch:watch];
                callback(SUCESS,NULL,NULL);
            }
            else
            {
                NSString *errorCode=[resdict valueForKey:@"errorCode"];
                NSLog(@"%@,setWatchInfo,fail,error code is %@",SyncManager_TAG,errorCode);
                callback(FAIL,NULL,[self getErrorInfo:errorCode]);
            }
            
            
        }];
    }
    @catch (NSException *exception) {
        NSLog(@"%@,setWatchInfo, exception is %@.",DATAMANAGER_TAG,exception.reason);
        
    }
}
-(void)updateRelation:(NSString *)deviceUid alias:(NSString *)alias completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    if(deviceUid==NULL||!([deviceUid intValue]>0)||alias==NULL)
    {
        NSLog(@"%@,updateRelation,parameter is illegal.",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,updateRelation,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"alias\":\"%@\" }",deviceUid,alias];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.updateRelation" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,updateRelation,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,updateRelation,result is sucess.",SyncManager_TAG);
            // 设置手表信息成功，更新到本地数据库
            [self.theManager updateRelation:deviceUid managerUid:user.uid alias:alias];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,updateRelation,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
    
}
//聊天相关接口API
/*
 群聊发送语音消息:ok
 */
-(void)uploadGroupChatRecord:(Chat *)chat completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,uploadGroupChatRecord entered. ",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,uploadGroupChatRecord,callback is null",SyncManager_TAG);
        return;
    }
    if(chat==NULL||chat.user_id==NULL)
    {
        NSLog(@"%@,uploadGroupChatRecord,parameters is illegal.",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,uploadGroupChatRecord,user is null.",DATAMANAGER_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *data=[NSString stringWithFormat:@"{\"groupId\":%d,\"type\":%d,\"genTime\":\"%@\",\"duration\":%d}",chat.groupId,chat.type,chat.genTime,chat.duration];

    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"ChatApiImpl.uploadGroupChatRecord" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    NSString *urlStr=[NSString stringWithFormat:@"%@://%@/v1/api/upload.json",protol,hostName];
    NSString *realPath=[[Tooler getDocumentDirectory] stringByAppendingString:chat.amr_url];
    [self.theRequeseter postFile:urlStr   fileName:chat.amr_name filePath:realPath param:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,uploadGroupChatRecord,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,uploadGroupChatRecord,result is sucess.",SyncManager_TAG);
            // 设置手表信息成功，更新到本地数据库
            NSString *seqId=[resdict valueForKey:@"seqId"];
            chat.sqeId=seqId;
            chat.is_send=1;
            [self.theManager updateChat:chat];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,uploadGroupChatRecord,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
      
    }];
}

/*
 单聊发送语音消息:ok
 */
-(void)uploadSingleChatRecord:(Chat *)chat completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,uploadSingleChatRecord entered. ",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,uploadSingleChatRecord,callback is null",SyncManager_TAG);
        return;
    }
    if(chat==NULL||chat.user_id==NULL)
    {
        NSLog(@"%@,uploadSingleChatRecord,parameters is illegal.",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,uploadSingleChatRecord,user is null.",DATAMANAGER_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *data=[NSString stringWithFormat:@"{\"targetUid\":%@,\"type\":%d,\"genTime\":\"%@\",\"duration\":%d}",chat.targetUid,chat.type,chat.genTime,chat.duration];

    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"ChatApiImpl.uploadSingleChatRecord" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    NSString *urlStr=[NSString stringWithFormat:@"%@://%@/v1/api/upload.json",protol,hostName];
    NSString *realPath=[[Tooler getDocumentDirectory] stringByAppendingString:chat.amr_url];
    [self.theRequeseter postFile:urlStr   fileName:chat.amr_name filePath:realPath param:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,uploadSingleChatRecord,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,uploadSingleChatRecord,result is sucess.",SyncManager_TAG);
            // 设置手表信息成功，更新到本地数据库
            chat.sqeId=[resdict valueForKey:@"seqId"];
            chat.is_send=1;
            [self.theManager updateChat:chat];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,uploadSingleChatRecord,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
        
    }];
}
/*
 群聊未读消息获取
 */
-(void)getGroupChatRecords:(int)groupId seqIdBegin:(NSString *)seqIdBegin limit:(int)limit deviceUid:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getGroupChatRecords entered. groupId is %d,limit is %d.",SyncManager_TAG,groupId,limit);
    if(callback==NULL)
    {
        NSLog(@"%@,getGroupChatRecords,callback is null",SyncManager_TAG);
        return;
    }
    if(!(groupId>0)||!(limit>0))
    {
        NSLog(@"%@,getGroupChatRecords,parameters is illegal.",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getGroupChatRecords,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    if(seqIdBegin==NULL||[seqIdBegin isEqualToString:@""]||[seqIdBegin isEqualToString:@"(null)"])
    {
        //seqIdBegin=@"1";
        //NSLog(@"%@,getGroupChatRecords,there is no chart data,stop to sync.",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    int seqIdEnd=[seqIdBegin intValue]+limit;
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"groupId\":%d,\"seqIdBegin\":%@,\"seqIdEnd\":%d,\"limit\":%d,\"order\":0 }",groupId,seqIdBegin,seqIdEnd,limit];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"ChatApiImpl.getGroupChatRecords" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getGroupChatRecords,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getGroupChatRecords,result is sucess.",SyncManager_TAG);
            //成功，更新到本地数据库
            NSMutableArray *chatList=[[NSMutableArray alloc] init];
            NSArray *chatData=[resdict valueForKey:@"records"];
            for(int i=0;i<[chatData count];i++)
            {
                NSDictionary *chatInfo=[chatData objectAtIndex:i];
                if(chatInfo==NULL)
                {
                    NSLog(@"%@,getGroupChatRecords,chatInfo is null, index is %d.",DATAMANAGER_TAG,i);
                    continue;
                }
                Chat *chat=[[Chat alloc] init];
                chat.groupId=groupId;
                chat.user_id=[chatInfo valueForKey:@"uid"];
                chat.type=[[chatInfo valueForKey:@"type"] intValue];
                chat.genTime=[chatInfo valueForKey:@"createTime"];
                chat.createTime=[chatInfo valueForKey:@"createTime"];
                chat.sqeId=[chatInfo valueForKey:@"seqId"];
                chat.duration=[[chatInfo  valueForKey:@"duration"] intValue];
                chat.pathHash=[chatInfo valueForKey:@"audioHash"];
                chat.accountId=user.uid;
                chat.deviceUid=deviceUid;
                chat.is_read=0;
                chat.is_view=0;
                chat.is_finish=0;
                chat.file_url=[chatInfo valueForKey:@"url"];
                chat.is_send=1;
                [chatList addObject:chat];
                chat=NULL;
                
            }
            if(chatList==NULL||[chatList count]==0)
            {
                NSLog(@"%@,getGroupChatRecords,chatList is null.",DATAMANAGER_TAG);
            }
            else
            {
                NSLog(@"%@,getGroupChatRecords,chatList count is %d.",DATAMANAGER_TAG,(int)[chatList count]);
                [self.theManager addChats:chatList];
                //下载聊天录音文件
                [self getChatFiles:chatList type:GROUPCHATFILE];
            }
            
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getGroupChatRecords,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];

}
-(void)getChatFiles:(NSMutableArray *)newChatLists type:(fileType)type
{
    NSLog(@"%@,getChatFiles entered.",SyncManager_TAG);
    if(newChatLists==NULL||[newChatLists count]==0)
    {
        NSLog(@"%@,getChatFiles,newChatLists is null.",SyncManager_TAG);
        return;
    }
    for(int i=0;i<[newChatLists count];i++)
    {
        Chat *chat=[newChatLists objectAtIndex:i];
        if(chat==NULL||chat.sqeId==NULL)
        {
            NSLog(@"%@,getChatFiles,chat is null,index is %d.",DATAMANAGER_TAG,i);
            continue;
        }
        //取新的提醒文件
        @try {
		
            dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            if(queue==NULL)
            {
                NSLog(@"%@,getChatFiles,queue is null",DATAMANAGER_TAG);
                return;
            }
            dispatch_async(queue, ^{
                if(type==GROUPCHATFILE)
                {
                    if(chat.file_url!=NULL&&![chat.file_url isEqualToString:@"(null)"]&&![chat.file_url isEqualToString:@""])
                    {
                        //[self getAudioByUrl:chat.pathHash url:chat.file_url theUid:chat.sqeId type:type otherId:[NSString stringWithFormat:@"%d",chat.groupId]];
                         [self getAudio:chat.pathHash theUid:chat.sqeId type:type otherId:[NSString stringWithFormat:@"%d",chat.groupId]];
                    }
                    else
                    {
                        [self getAudio:chat.pathHash theUid:chat.sqeId type:type otherId:[NSString stringWithFormat:@"%d",chat.groupId]];
                    }
                }
                else if(type==SINGLEFILE)
                {
                    if(chat.file_url!=NULL&&![chat.file_url isEqualToString:@"(null)"]&&![chat.file_url isEqualToString:@""])
                    {
                        //[self getAudioByUrl:chat.pathHash url:chat.file_url theUid:chat.sqeId type:type otherId:chat.targetUid];
                        [self getAudio:chat.pathHash theUid:chat.sqeId type:type otherId:chat.targetUid];
                    }
                    else
                    {
                        [self getAudio:chat.pathHash theUid:chat.sqeId type:type otherId:chat.targetUid];
                    }
                }
                
                
            });
            
        }
        @catch (NSException *exception) {
            NSLog(@"%@,getChatFiles,exception is %@",DATAMANAGER_TAG,[exception reason]);
        }

    }
}
/*
  单聊未读消息获取
 */
-(void)getSingleChatRecords:(NSString *)targetUid seqIdBegin:(NSString *)seqIdBegin limit:(int)limit deviceUid:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getSingleChatRecords entered. targetUid is %@,limit is %d,deviceUid is %@.",SyncManager_TAG,targetUid,limit,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,getSingleChatRecords,callback is null",SyncManager_TAG);
        return;
    }
    if(!([targetUid intValue]>0)||!(limit>0))
    {
        NSLog(@"%@,getSingleChatRecords,parameters is illegal.",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getSingleChatRecords,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    if(seqIdBegin==NULL||[seqIdBegin isEqualToString:@"(null)"]||[seqIdBegin isEqualToString:@""])
    {
        //seqIdBegin=@"1";
        //NSLog(@"%@,getSingleChatRecords,there is no chart data,stop to sync.",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    int seqIdEnd=[seqIdBegin intValue]+limit;
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"targetUid\":%@,\"seqIdBegin\":%@,\"seqIdEnd\":%d,\"limit\":%d,\"order\":0}",targetUid,seqIdBegin,seqIdEnd,limit];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"ChatApiImpl.getSingleChatRecords" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getSingleChatRecords,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getSingleChatRecords,result is sucess.",SyncManager_TAG);
            //成功，更新到本地数据库
            NSMutableArray *chatList=[[NSMutableArray alloc] init];
            NSArray *chatData=[resdict valueForKey:@"records"];
            for(int i=0;i<[chatData count];i++)
            {
                NSDictionary *chatInfo=[chatData objectAtIndex:i];
                if(chatInfo==NULL)
                {
                    NSLog(@"%@,getSingleChatRecords,chatInfo is null, index is %d.",DATAMANAGER_TAG,i);
                    continue;
                }
                Chat *chat=[[Chat alloc] init];
                chat.targetUid=[chatInfo valueForKey:@"targetUid"];
                chat.user_id=[chatInfo valueForKey:@"uid"];
                chat.type=[[chatInfo valueForKey:@"type"] intValue];
                chat.genTime=[chatInfo valueForKey:@"createTime"];
                chat.createTime=[chatInfo valueForKey:@"createTime"];
                chat.sqeId=[chatInfo valueForKey:@"seqId"];
                chat.duration=[[chatInfo  valueForKey:@"duration"] intValue];
                chat.pathHash=[chatInfo valueForKey:@"audioHash"];
                chat.accountId=user.uid;
                chat.deviceUid=deviceUid;
                chat.is_read=0;
                chat.is_view=0;
                chat.file_url=[chatInfo valueForKey:@"url"];
                chat.is_send=1;
                [chatList addObject:chat];
                chat=NULL;
                
            }
            if(chatList==NULL||[chatList count]==0)
            {
                NSLog(@"%@,getSingleChatRecords,chatList is null.",DATAMANAGER_TAG);
            }
            else
            {
                NSLog(@"%@,getSingleChatRecords,chatList count is %d.",DATAMANAGER_TAG,(int)[chatList count]);
                [self.theManager addChats:chatList];
                //下载录音文件
                [self getChatFiles:chatList type:SINGLEFILE];
            }
            
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getSingleChatRecords,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
}



// 定位相关API
/*
 app设置手表定位参数:ok
 
 */
-(void)setLocateParameters:(NSString *)deviceUid reportInterval:(int) reportInterval sampleInterval:(int)sampleInterval completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,setLocateParameters entered. deviceUid is %@,reportInterval is %d,sampleInterval is %d.",SyncManager_TAG,deviceUid,reportInterval,sampleInterval);
    if(callback==NULL)
    {
        NSLog(@"%@,setLocateParameters,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0||reportInterval<0||sampleInterval<0)
    {
        NSLog(@"%@,setLocateParameters,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,setLocateParameters,user is null",SyncManager_TAG);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"locateReportInterval\":%d,\"locateSampleInterval\":%d}",deviceUid,reportInterval,sampleInterval];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"LocationApiImpl.setLocateParameters" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,setLocateParameters,resdict is null",SyncManager_TAG);
            callback(FAIL,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,setLocateParameters success.",SyncManager_TAG);
            //设置成功，更新到数据库中
            [self.theManager updateLocateParameters:deviceUid reportInterval:reportInterval sampleInterval:sampleInterval];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,setLocateParameters,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
}

/*
 app获取手表定位参数:ok
 
 */
-(void)getLocateParameters:(NSString *)deviceUid  completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getLocateParameters entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,getLocateParameters,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0)
    {
        NSLog(@"%@,getLocateParameters,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getLocateParameters,user is null",SyncManager_TAG);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@}",deviceUid];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"LocationApiImpl.getLocateParameters" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getLocateParameters,resdict is null",SyncManager_TAG);
            callback(FAIL,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getLocateParameters success.",SyncManager_TAG);
            //获取定位参数成功,解析数据，更新本地数据库
            float reportInterval=[[resdict valueForKey:@"reportReportInterval"] floatValue];
            float sampleInterval=[[resdict valueForKey:@"locateSampleInterval"] floatValue];
            [self.theManager updateLocateParameters:deviceUid reportInterval:reportInterval sampleInterval:sampleInterval];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getLocateParameters,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
}
/*
 app添加地理围栏：ok
 
 */
-(void)addGeoFence:(NSString *)deviceUid fence:(Fence *)fence completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,addGeoFence entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,addGeoFence,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0||fence==NULL)
    {
        NSLog(@"%@,addGeoFence,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,addGeoFence,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"geoFence\":{\"type\":%d,\"radius\":%f,\"cycle\":\"%@\",\"longtitude\":%f,\"latitude\":%f,\"startTime\":'%@',\"endTime\":'%@',\"description\":\"%@\",\"title\":\"%@\",\"active\":%d}}",deviceUid,fence.type,fence.radius,fence.cycle,fence.longtitude,fence.latitude,fence.start_time,fence.end_time,fence.desc,fence.title,fence.is_active];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"LocationApiImpl.addGeoFence" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,addGeoFence,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,addGeoFence success.",SyncManager_TAG);
            //设置成功，解析地理围栏数据，存数据库
            fence.fence_id=[resdict valueForKey:@"id"];
            [self.theManager addFence:fence];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,addGeoFence,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
}
/*
  app设置地理围栏:ok
 
*/
-(void) setGeoFence:(NSString *)deviceUid fence:(Fence *)fence completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,setGeoFence entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,setGeoFence,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0||fence==NULL||[fence.fence_id intValue]<=0)
    {
        NSLog(@"%@,setGeoFence,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,setGeoFence,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"geoFence\":{\"id\":%@,\"type\":%d,\"radius\":%f,\"cycle\":\"%@\",\"longtitude\":%f,\"latitude\":%f,\"startTime\":'%@',\"endTime\":'%@',\"description\":\"%@\",\"title\":\"%@\",\"active\":%d}}",deviceUid,fence.fence_id,fence.type,fence.radius,fence.cycle,fence.longtitude,fence.latitude,fence.start_time,fence.end_time,fence.desc,fence.title,fence.is_active];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"LocationApiImpl.setGeoFence" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,setGeoFence,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,setGeoFence success.",SyncManager_TAG);
             //设置成功，解析地理围栏数据，存数据库
            [self.theManager updateFence:fence];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,setGeoFence,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
}
/*
 获取地理围栏:ok
 
 */
-(void)getGeoFences:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getGeoFences entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,getGeoFences,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0)
    {
        NSLog(@"%@,getGeoFences,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getGeoFences,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *ts=[self.theManager getFenceTS:deviceUid];
    if([ts isEqualToString:@"(null)"]||ts==NULL||[ts isEqualToString:@""])
    {
        ts=@"null";
    }
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"ts\":'%@'}",deviceUid,ts];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"LocationApiImpl.getGeoFences" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getGeoFences,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getGeoFences success.",SyncManager_TAG);
            //解析获取到的数据，更新到本地数据库
            NSString *updateTime=[resdict valueForKey:@"ts"];
            NSArray *geoFences=[resdict valueForKey:@"geoFences"];
            if(geoFences==NULL||[geoFences count]==0)
            {
                NSLog(@"%@,getGeoFences,has no fence data.",DATAMANAGER_TAG);
                callback(SUCESS,NULL,NULL);
                return;
            }
            NSMutableArray *fenceData=[[NSMutableArray alloc] init];
            for (int i=0; i<[geoFences count]; i++) {
                NSDictionary *geoData=[geoFences objectAtIndex:i];
                if(geoData==NULL||[geoData count]<=0)
                {
                    NSLog(@"%@,getGeoFences,geo data is null.",SyncManager_TAG);
                    continue;
                }
                Fence *fence=[[Fence alloc] init];
                if(fence==NULL)
                {
                    NSLog(@"%@,getGeoFences,fence is null.",DATAMANAGER_TAG);
                    continue;
                }
                fence.latitude=[[geoData valueForKey:@"latitude"] floatValue];
                fence.longtitude=[[geoData valueForKey:@"longtitude"] floatValue];
                fence.altitude=[[geoData valueForKey:@"altitude"] floatValue];
                fence.desc=[geoData valueForKey:@"description"];
                fence.radius=[[geoData valueForKey:@"radius"] floatValue];
                fence.title=[geoData valueForKey:@"title"];
                fence.start_time=[geoData valueForKey:@"startTime"];
                fence.end_time=[geoData valueForKey:@"endTime"] ;
                fence.cycle=[geoData valueForKey:@"cycle"];
                fence.is_active=[[geoData valueForKey:@"active"] floatValue];
                fence.deviceUid=deviceUid;
                fence.fence_id=[geoData valueForKey:@"id"];
                fence.type=[[geoData valueForKey:@"type"] intValue];
                fence.action=[[geoData valueForKey:@"action"] intValue];
                fence.updateTime=updateTime;
                [fenceData addObject:fence];
                fence=NULL;
            }
            if(fenceData!=NULL&&[fenceData count]>0)
            {
                [self.theManager updateFences:fenceData];
            }
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getGeoFences,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
        
    }];
}
/*
 删除地理围栏:ok
 
  */
-(void)deleteGeoFence:(NSString *)deviceUid fenceId:(NSString *)fenceId completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,deleteGeoFence entered. deviceUid is %@,fenceId is %@.",SyncManager_TAG,deviceUid,fenceId);
    if(callback==NULL)
    {
        NSLog(@"%@,deleteGeoFence,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||!([deviceUid intValue]>0)||fenceId==NULL||!([fenceId intValue]>0))
    {
        NSLog(@"%@,deleteGeoFence,parameters is illegal",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,deleteGeoFence,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"geoFence\":{\"id\":%@}}",deviceUid,fenceId];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"LocationApiImpl.deleteGeoFence" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,deleteGeoFence,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,deleteGeoFence success.",SyncManager_TAG);
            //删除成功，更新本地数据库
            [self.theManager deleteFence:fenceId deviceUid:deviceUid];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,deleteGeoFence,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];

}
/*
 获取手表的运动轨迹:ok
 
 */
-(void)getMotionTrack:(NSString *)deviceUid withStartTime:(NSString *)startTime andEndTime:(NSString *)endTime completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getMotionTrack entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,getMotionTrack,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0)
    {
        NSLog(@"%@,getMotionTrack,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getMotionTrack,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;

    if(startTime == NULL || [startTime isEqualToString:@"(null)"] || [startTime isEqualToString:@""] || [startTime isEqualToString:@"null"]) {
        startTime = @"null";
    } else {
        startTime = [Tooler strToTime:startTime];
    }

    if(endTime == NULL || [endTime isEqualToString:@"(null)"] || [endTime isEqualToString:@""] || [endTime isEqualToString:@"null"]) {
        endTime = [Tooler getTS];
    } else {
        endTime = [Tooler strToTime:endTime];
    }

    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"startTime\":%@,\"endTime\":%@}",deviceUid,startTime,endTime];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"LocationApiImpl.getMotionTrack" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];

    
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getMotionTrack,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getMotionTrack success.",SyncManager_TAG);
            //获取运动轨迹成功，更新本地数据库
            NSArray *locArray=[resdict valueForKey:@"locationData"];
            if(locArray==NULL||[locArray count]==0)
            {
                NSLog(@"%@,has no location data.",SyncManager_TAG);
                callback(SUCESS,NULL,NO_DATA);
                return;
            }
            else
            {
                NSMutableArray *locationArray=[[NSMutableArray alloc] init];
                for (int i=0; i<[locArray count]; i++) {
                    Location *location=[[Location alloc] init];
                    if(location==NULL)
                    {
                        NSLog(@"%@,getMotionTrack,location is null.",SyncManager_TAG);
                        continue;
                    }
                    NSDictionary *locData=[locArray objectAtIndex:i];
                    if(locData==NULL||[locData count]<=0)
                    {
                        NSLog(@"%@,getMotionTrack,locData is null.",DATAMANAGER_TAG);
                        continue;
                    }
                    location.deviceUid=deviceUid;
                    location.latitude=[[locData valueForKey:@"latitude"] floatValue];
                    location.longtitude=[[locData valueForKey:@"longtitude"] floatValue];
                    location.radius=[[locData valueForKey:@"radius"] floatValue];
                    location.type=[[locData valueForKey:@"type"] intValue];
                    location.updateTime=[resdict valueForKey:@"ts"];
                    location.gen_time=[locData valueForKey:@"createTime"];
                    location.locateType=[[locData valueForKey:@"locateType"] intValue];
                    location.mainAddress=[locData valueForKey:@"street"];
                    location.subAddress=[locData valueForKey:@"description"];
                    NSLog(@"getMotionTrack: Debug for TianAnMen: %f, %f, %@, %@, %@, when i == %i", location.latitude, location.longtitude, location.mainAddress, location.subAddress, location.gen_time, i);
                    
                    [locationArray addObject:location];
                    location=NULL;
                    
                }
                if(locationArray==NULL||[locationArray count]==0)
                {
                    NSLog(@"%@,getMotionTrack,locationArray is null.",SyncManager_TAG);
                }
                else
                {
                    [self.theManager addPosition:locationArray];
                }
            }
            callback(SUCESS,NULL,NULL);
            //设置数据
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getMotionTrack,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
        
    }];

}
/*
 获取手表最新位置信息:ok
 */
-(void)getLatestPosition:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getLatestPosition entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,getLatestPosition,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0)
    {
        NSLog(@"%@,getLatestPosition,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getLatestPosition,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@}",deviceUid];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"LocationApiImpl.getLastPosition" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getLatestPosition,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getLatestPosition success.",SyncManager_TAG);
            //解析数据，更新本地数据库
            NSDictionary *locationData=[resdict valueForKey:@"location"];
            Location *location=[[Location alloc] init];
            if(location!=NULL)
            {
                location.deviceUid=deviceUid;
                location.latitude=[[locationData valueForKey:@"latitude"] floatValue];
                location.longtitude=[[locationData valueForKey:@"longtitude"] floatValue];
                location.radius=[[locationData valueForKey:@"radius"] floatValue];
                location.type=[[locationData valueForKey:@"type"] intValue];
                location.gen_time=[locationData valueForKey:@"createTime"];
                location.locateType=[[locationData valueForKey:@"locateType"] intValue];
                location.mainAddress=[locationData valueForKey:@"street"];
                location.subAddress=[locationData valueForKey:@"description"];
                NSMutableArray *locArray=[[NSMutableArray alloc] init];
                [locArray addObject:location];
                if(locArray!=NULL&&[locArray count]>0)
                {
                    [self.theManager addPosition:locArray];
                }
                
            }
            callback(SUCESS,NULL,NULL);
            
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getLatestPosition,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
}
/*
 手表立即定位:ok
 
 */
-(void)locateImmediately:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,locateImmediately entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,locateImmediately,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0)
    {
        NSLog(@"%@,locateImmediately,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,locateImmediately,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@}",deviceUid];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"LocationApiImpl.locateImmdediately" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,locateImmediately,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,locateImmediately success.",SyncManager_TAG);
            [self getLatestPosition:deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if (result == SUCESS) {
                    NSLog(@"%@,after locateImmediately success, sync LastPosition success.",SyncManager_TAG);
                    callback(SUCESS,NULL,NULL);
                }else{
                    callback(FAIL,NULL,NULL);
                }
                
            }];
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,locateImmediately,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
}

-(SyncResult)checkValid
{
    
    //判断当前网络状况
    if([Tooler checkNetworkState]==3)
    {
        return NO_NET_WORK;
    }
    if(self.theRequeseter==NULL)
    {
        NSLog(@"%@,checkValid,theRequeseter is null",SyncManager_TAG);
        return ERROR;
    }
    if(self.theDbHelper==NULL)
    {
        NSLog(@"%@,checkValid,theDbHelper is null",SyncManager_TAG);
        return ERROR;
    }

    return SUCESS;
}
-(NSString *)getErrorInfo:(NSString *)errorCode
{
    NSLog(@"%@,getErrorInfo enter. error code is %@",SyncManager_TAG,errorCode);
    if(errorCode==NULL||[errorCode intValue]<0)
    {
        NSLog(@"%@,getErrorInfo , error code is illegal",SyncManager_TAG);
        return NULL;
    }
    NSString *description=NULL;
    switch ([errorCode intValue]) {
        case USER_UNEXIST: description=USER_UNEXIST_INFO;break;
        case DEVICE_ID_ILLEGAL: description=DEVICE_ID_ILLEGAL_INFO;break;
        case USER_ID_ILLEGAL: description=USER_ID_ILLEGAL_INFO;break;
        case USER_PERMISSION_NOT_ALLOWED: description=USER_PERMISSION_NOT_ALLOWED_INFO;break;
        case USER_DEVICE_NOT_BOUND: description=USER_DEVICE_NOT_BOUND_INFO;break;
        case USER_REQUEST_ILLEGAL: description=USER_REQUEST_ILLEGAL_INFO;break;
        case USER_BIND_DEVICE_NULL: description=USER_BIND_DEVICE_NULL_INFO;break;
        case SMSCODE_VERIFY_FAILED:description=SMSCODE_VERIFY_FAILED_INFO;break;
        case USER_ALREADY_EXIST:description=USER_ALREADY_EXIST_INFO;break;
        case USER_ACCESS_TOKEN_EXPIRED:description=USER_ACCESS_TOKEN_EXPIRED_INFO;break;
        case USER_PWD_NOT_MATCH_USER:description=USER_PWD_NOT_MATCH_USER_INFO;break;
        case USER_LOGINED_ON_OTHER_DEVICE:description=USER_LOGINED_ON_OTHER_DEVICE_INFO;break;
        case USER_VERIFY_CODE_ILLEGAL:description=USER_VERIFY_CODE_ILLEGAL_INFO;break;
        case USER_UPDATE_PWD_FAILURE:description=USER_UPDATE_PWD_FAILURE_INFO;break;
        case USER_BIND_REQUEST_REJECTED:description=USER_BIND_REQUEST_REJECTED_INFO;break;
        case USER_PHONENUM_NONEXIST:description=USER_PHONENUM_NONEXIST_INFO;break;
        case USER_PHONENUM_ALREADY_REGISTER:description=USER_PHONENUM_ALREADY_REGISTER_INFO;break;
        case USER_FULLNAME_NONEXIST:description=USER_FULLNAME_NONEXIST_INFO;break;
        case USER_ACCOUNT_ALREADYEXIST:description=USER_ACCOUNT_ALREADYEXIST_INFO;break;
        case USER_GEOFENCE_IS_NULL:description=USER_GEOFENCE_IS_NULL_INFO;break;
        case USER_GEOFENCE_NON_EXIST:description=USER_GEOFENCE_NON_EXIST_INFO;break;
        case USER_GEOFENCE_ALREADY_DELETED:description=USER_GEOFENCE_ALREADY_DELETED_INFO;break;
        case USER_CONTACT_ALREADY_EXIST:description=USER_CONTACT_ALREADY_EXIST_INFO;break;
        case USER_CONTACT_NONEXIST:description=USER_CONTACT_NONEXIST_INFO;break;
        case USER_CONTACT_ALREADY_DELETED:description=USER_CONTACT_ALREADY_DELETED_INFO;break;
        case USER_REMINDER_ALREADY_EXIST:description=USER_REMINDER_ALREADY_EXIST_INFO;break;
        case USER_REMINDER_NONEXIST:description=USER_REMINDER_NONEXIST_INFO;break;
        case USER_REMINDER_ALREADY_DELETED:description=USER_REMINDER_ALREADY_DELETED_INFO;break;
        case USER_SILENTPERIOD_ALREADY_EXIST:description=USER_SILENTPERIOD_ALREADY_EXIST_INFO;break;
        case USER_SILENTPERIOD_NONEXIST:description=USER_SILENTPERIOD_NONEXIST_INFO;break;
        case USER_SILENTPERIOD_ALREADY_DELETED:description=USER_SILENTPERIOD_ALREADY_DELETED_INFO;break;
        case DEVICE_ALREADY_BOUND:description=DEVICE_ALREADY_BOUND_INFO;break;
        case SMS_SEND_FAILURE:description=SMS_SEND_FAILURE_INFO;break;
        case SMS_COUNT_REACH_UPPER_LIMIT:description=SMS_COUNT_REACH_UPPER_LIMIT_INFO;break;
        case SMS_VERIFY_FAILURE:description=SMS_VERIFY_FAILURE_INFO;break;
        case SMS_FREQUENCY_TOO_FAST:description=SMS_FREQUENCY_TOO_FAST_INFO;break;
        case SYSTEM_INNER_ERROR:description=SYSTEM_INNER_ERROR_INFO;break;
        case API_INVOCATION_FAILED:description=API_INVOCATION_FAILED_INFO;break;
        case GROUP_USER_NOT_IN_ONE_GROUP:description=GROUP_USER_NOT_IN_ONE_GROUP_INFO;break;
        case DEVICE_VERSION_IS_NEWEST:description=DEVICE_VERSION_IS_NEWEST_INFO;break;
        case APP_VERSION_IS_NEWEST:description=APP_VERSION_IS_NEWEST_INFO;break;
        case API_REFRESHTOKEN_INVALID:description=API_REFRESHTOKEN_INVALID_INFO;break;
        case DEVICE_OFFLINE:description=DEVICE_OFFLINE_INFO;break;
        case USER_BOUND_DEVICE_UP_TO_LIMIT:description=USER_BOUND_DEVICE_UP_TO_LIMIT_INFO;break;
        case USER_NUM_UP_TO_LIMIT:description=USER_NUM_UP_TO_LIMIT_INFO;break;
        default:
            description=[NSString stringWithFormat:@"unknown error:%@",errorCode];
            break;
    }
    return description;
}


/**********************************************
静音时段相关接口
 **********************************************/

/*
 app添加静音时段:ok
 */
-(void)addSilentPeriod:(NSString *)deviceUid silent:(Silent *)silent completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,addSilentPeriod entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,addSilentPeriod,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0||silent==NULL)
    {
        NSLog(@"%@,addSilentPeriod,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,addSilentPeriod,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *silentPeriod=[NSString stringWithFormat:@"{\"cycle\":\"%@\",\"description\":\"%@\",\"endTime\":\"%@\",\"startTime\":\"%@\",\"title\":\"%@\",\"active\":%d }",silent.cycle,silent.desc,silent.endTime,silent.startTime,silent.title,silent.active];
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"silentPeriod\":%@}",deviceUid,silentPeriod];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.addSilentPeriod" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,addSilentPeriod,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,addSilentPeriod success.",SyncManager_TAG);
            silent.slient_id=[resdict valueForKey:@"id"];
            //设置数据
            [self.theManager addSilent:silent deviceUid:deviceUid];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,addSilentPeriod,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
    
}

/*
 app更新静音时段:ok
 */
-(void)setSilentPeriod:(NSString *)deviceUid silent:(Silent *)silent completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,setSilentPeriod entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,setSilentPeriod,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0||silent==NULL)
    {
        NSLog(@"%@,setSilentPeriod,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,setSilentPeriod,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *silentPeriod=[NSString stringWithFormat:@"{\"id\":%@,\"cycle\":\"%@\",\"description\":\"%@\",\"endTime\":'%@',\"startTime\":'%@',\"title\":\"%@\",\"active\":%d }",silent.slient_id,silent.cycle,silent.desc,silent.endTime,silent.startTime,silent.title,silent.active];
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":\"%@\",\"silentPeriod\":%@}",deviceUid,silentPeriod];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.setSilentPeriod" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,setSilentPeriod,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,setSilentPeriod success.",SyncManager_TAG);
            
            //设置数据
            [self.theManager updateSilent:silent deviceUid:deviceUid];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,setSilentPeriod,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];

}
/*
 删除静音时段:ok
 */
-(void)deleteSilent:(NSString *)deviceUid silentId:(NSString *)silentId completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,deleteSilent entered. deviceUid is %@,silentId is %@.",SyncManager_TAG,deviceUid,silentId);
    if(callback==NULL)
    {
        NSLog(@"%@,deleteSilent,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0||silentId==NULL||!([silentId intValue]>0))
    {
        NSLog(@"%@,deleteSilent,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,deleteSilent,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"silentPeriod\":{\"id\":%@}}",deviceUid,silentId];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.deleteSilentPeriod" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,deleteSilent,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,deleteSilent success.",SyncManager_TAG);
            //设置数据
            [self.theManager deleteSilent:silentId deviceUid:deviceUid];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,deleteSilent,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];

}
/*
 获取静音时段:ok
 */
-(void)getSilent:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getSilent entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,getSilent,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0)
    {
        NSLog(@"%@,getSilent,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getSilent,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *ts=[self.theManager getEventTS:deviceUid];
    if(ts==NULL||[ts isEqualToString:@"(null)"]||[ts isEqualToString:@""])
    {
        ts=@"null";
    }
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":\"%@\",\"ts\":%@}",deviceUid,ts];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getSilentPeriods" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getSilent,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getSilent success.",SyncManager_TAG);
            NSString *updateTime=[resdict valueForKey:@"ts"];
            NSArray *silentData=[resdict valueForKey:@"periods"];
            if(silentData==NULL||[silentData count]==0)
            {
                NSLog(@"%@,getSilent,silenData count is 0.",SyncManager_TAG);
            }
            else
            {
                NSMutableArray *silentList=[[NSMutableArray alloc] init];
                if(silentList==NULL)
                {
                    NSLog(@"%@,getSilent,silentList is null.",SyncManager_TAG);
                }
                else
                {
                    for(int i=0;i<[silentData count];i++)
                    {
                        NSDictionary *silentInfo=[silentData objectAtIndex:i];
                        if(silentInfo==NULL||[silentInfo count]==0)
                        {
                            NSLog(@"%@,getSilent,silentInfo is null,index is %d.",DATAMANAGER_TAG,i);
                            continue;
                        }
                        Silent *silent=[[Silent alloc] init];
                        if(silent!=NULL)
                        {
                            silent.action=[[silentInfo valueForKey:@"action"] intValue];
                            silent.cycle=[silentInfo valueForKey:@"cycle"];
                            silent.desc=[silentInfo valueForKey:@"description"];
                            silent.endTime=[silentInfo valueForKey:@"endTime"];
                            silent.slient_id=[silentInfo valueForKey:@"id"];
                            silent.startTime=[silentInfo valueForKey:@"startTime"];
                            silent.title=[silentInfo valueForKey:@"title"];
                            silent.active=[[silentInfo valueForKey:@"active"] intValue];
                            silent.updateTime=updateTime;
                            [silentList addObject:silent];
                            silent=NULL;
                        }
                        
                    }
                    if([silentList count]==0)
                    {
                        NSLog(@"%@,getSilent,there is no silent data.",SyncManager_TAG);
                    }
                    else
                    {
                        //更新本地数据库
                        [self.theManager updateSilents:silentList deviceUid:deviceUid];
                    }
                }
            }
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getSilent,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
}
/***************************************************
 提醒相关API
 ***************************************************/
/*
 添加提醒:ok
 */
-(void)addReminder:(NSString *)deviceUid reminder:(Reminder *)reminder completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,addReminder entered,deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,addReminder,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||!([deviceUid intValue]>0)||reminder==NULL)
    {
        NSLog(@"%@,addReminder,parameters is illegal.",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,addReminder,user is null.",DATAMANAGER_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"reminder\":{\"active\":%d,\"cycle\":\"%@\",\"remindTime\":\"%@\",\"title\":\"%@\",\"description\":\"%@\",\"type\":%d}}",deviceUid,reminder.is_active,reminder.cycle,reminder.remindTime,reminder.title,reminder.desc,reminder.type];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.addReminder" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    NSString *urlStr=[NSString stringWithFormat:@"%@://%@/v1/api/upload.json",protol,hostName];
    NSString *filePath=NULL;
    if(reminder.amrUrl!=NULL)
    {
        filePath=[[Tooler getDocumentDirectory] stringByAppendingString:reminder.amrUrl];
    }
    @try {
        
        [self.theRequeseter postFile:urlStr  fileName:NULL filePath:filePath param:param completion:^(NSDictionary *resdict) {
            if(resdict==NULL||[resdict count]==0)
            {
                NSLog(@"%@,addReminder,resdict is null",SyncManager_TAG);
                callback(NODATA,NULL,NULL);
                return;
            }
            NSString *ret=[resdict valueForKey:@"success"];
            if(ret!=NULL&&[ret intValue]==1)
            {
                NSLog(@"%@,addReminder,result is sucess.",SyncManager_TAG);
                // 新增联系人成功，更新到本地数据库
                reminder.reminder_id=[resdict valueForKey:@"id"];
                reminder.audioHash=[resdict valueForKey:@"audioHash"];
                [self.theManager addReminder:reminder deviceUid:deviceUid];
                callback(SUCESS,NULL,NULL);
            }
            else
            {
                NSString *errorCode=[resdict valueForKey:@"errorCode"];
                NSLog(@"%@,addReminder,fail,error code is %@",SyncManager_TAG,errorCode);
                callback(FAIL,NULL,[self getErrorInfo:errorCode]);
            }
        }];
        
    }
    @catch (NSException *ex) {
        NSLog(@"%@,addReminder,exception is %@",SyncManager_TAG,ex.reason);
    }

    

}
/*
 更新提醒:ok
 */
-(void)setReminder:(NSString *)deviceUid reminder:(Reminder *)reminder completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,setReminder entered,deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,setReminder,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||!([deviceUid intValue]>0)||reminder==NULL)
    {
        NSLog(@"%@,setReminder,parameters is illegal.",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,setReminder,user is null.",DATAMANAGER_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"reminder\":{\"id\":%@,\"active\":%d,\"cycle\":\"%@\",\"remindTime\":\"%@\",\"title\":\"%@\",\"description\":\"%@\",\"type\":%d}}",deviceUid,reminder.reminder_id,reminder.is_active,reminder.cycle,reminder.remindTime,reminder.title,reminder.desc,reminder.type];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.setReminder" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    NSString *urlStr=[NSString stringWithFormat:@"%@://%@/v1/api/upload.json",protol,hostName];
    NSString *filePath=NULL;
    if(reminder.amrUrl!=NULL)
    {
        filePath=[[Tooler getDocumentDirectory] stringByAppendingString:reminder.amrUrl];
    }

    @try {
        
        [self.theRequeseter postFile:urlStr  fileName:NULL filePath:filePath param:param completion:^(NSDictionary *resdict) {
            if(resdict==NULL||[resdict count]==0)
            {
                NSLog(@"%@,setReminder,resdict is null",SyncManager_TAG);
                callback(NODATA,NULL,NULL);
                return;
            }
            NSString *ret=[resdict valueForKey:@"success"];
            if(ret!=NULL&&[ret intValue]==1)
            {
                NSLog(@"%@,setReminder,result is sucess.",SyncManager_TAG);
                // 更新到本地数据库
                reminder.audioHash=[resdict valueForKey:@"audioHash"];
                [self.theManager updateReminder:reminder deviceUid:deviceUid];
                callback(SUCESS,NULL,NULL);
            }
            else
            {
                NSString *errorCode=[resdict valueForKey:@"errorCode"];
                NSLog(@"%@,setReminder,fail,error code is %@",SyncManager_TAG,errorCode);
                callback(FAIL,NULL,[self getErrorInfo:errorCode]);
            }
        }];
        
    }
    @catch (NSException *ex) {
        NSLog(@"%@,setReminder,exception is %@",SyncManager_TAG,ex.reason);
    }
    
    

}
/*
 删除提醒:ok
 */
-(void)deleteReminder:(NSString *)deviceUid reminderId:(NSString *)reminderId completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,deleteReminder entered. deviceUid is %@,reminderId is %@.",SyncManager_TAG,deviceUid,reminderId);
    if(callback==NULL)
    {
        NSLog(@"%@,deleteReminder,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0||reminderId==NULL||!([reminderId intValue]>0))
    {
        NSLog(@"%@,deleteReminder,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,deleteReminder,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"reminder\":{\"id\":%@}}",deviceUid,reminderId];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.deleteReminder" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,deleteReminder,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,deleteReminder success.",SyncManager_TAG);
            //设置数据
            [self.theManager deleteReminder:reminderId deviceUid:deviceUid];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,deleteReminder,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
    

}
/*
 获取所有提醒:ok,提醒文件有问题
 */
-(void)getReminders:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getReminders entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,getReminders,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0)
    {
        NSLog(@"%@,getReminders,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getReminders,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *ts=[self.theManager getRemindTs:deviceUid];
    if(ts==NULL||[ts isEqualToString:@"(null)"]||[ts isEqualToString:@""])
    {
        ts=@"null";
    }
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":\"%@\",\"ts\":%@}",deviceUid,ts];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getReminders" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getReminders,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getReminders success.",SyncManager_TAG);
            NSString *updateTime=[resdict valueForKey:@"ts"];
            NSArray *remindData=[resdict valueForKey:@"reminds"];
            if(remindData==NULL||[remindData count]==0)
            {
                NSLog(@"%@,getReminders,silenData count is 0.",SyncManager_TAG);
            }
            else
            {
                NSMutableArray *remindList=[[NSMutableArray alloc] init];
                if(remindList==NULL)
                {
                    NSLog(@"%@,getReminders,silentList is null.",SyncManager_TAG);
                }
                else
                {
                    for(int i=0;i<[remindData count];i++)
                    {
                        NSDictionary *remindInfo=[remindData objectAtIndex:i];
                        if(remindInfo==NULL||[remindInfo count]==0)
                        {
                            NSLog(@"%@,getReminders,remindInfo is null,index is %d.",DATAMANAGER_TAG,i);
                            continue;
                        }
                        Reminder *reminder=[[Reminder alloc] init];
                        if(reminder!=NULL)
                        {
                            reminder.reminder_id=[remindInfo valueForKey:@"id"];
                            reminder.is_active=[[remindInfo valueForKey:@"active"] intValue];
                            reminder.action=[[remindInfo valueForKey:@"action"] intValue];
                            reminder.cycle=[remindInfo valueForKey:@"cycle"];
                            reminder.audioHash=[remindInfo valueForKey:@"audioHash"];
                            reminder.remindTime=[remindInfo valueForKey:@"remindTime"];
                            reminder.title=[remindInfo valueForKey:@"title"];
                            reminder.desc=[remindInfo valueForKey:@"description"];
                            reminder.type=[[remindInfo valueForKey:@"type"] intValue];
                            reminder.updateTime=updateTime;
                            reminder.audioUrl=[remindInfo valueForKey:@"url"];
                            reminder.autionTime=[[remindInfo valueForKey:@"duration"] intValue];
                            [remindList addObject:reminder];
                            reminder=NULL;
                        }
                        
                    }
                    if([remindList count]==0)
                    {
                        NSLog(@"%@,getReminders,there is no silent data.",SyncManager_TAG);
                    }
                    else
                    {
                        //更新本地数据库
                        [self.theManager updateReminds:remindList devieUid:deviceUid];
                        //下载新的提醒文件
                        [self getRemindFiles:remindList deviceUid:deviceUid];
                    }
                }
            }
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getReminders,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];

}
-(void)getRemindFiles:(NSMutableArray *)newRemindList deviceUid:(NSString *)deviceUid
{
    NSLog(@"%@,getRemindFiles entered,deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(newRemindList==NULL||[newRemindList count]==0||deviceUid==NULL||!([deviceUid intValue]>0))
    {
        NSLog(@"%@,getRemindFiles,newRemindList is null.",SyncManager_TAG);
        return;
    }
    //读取已有audioHash
    NSMutableDictionary *oldRemindList=[self.theManager getRemindAudioHash:deviceUid];
    for(int i=0;i<[newRemindList count];i++)
    {
        Reminder *reminder=[newRemindList objectAtIndex:i];
        if(reminder==NULL||reminder.audioHash==NULL||[reminder.audioHash isEqualToString:@"(null)"]||reminder.action==0)
        {
            NSLog(@"%@,getRemindFiles,reminder is null.",DATAMANAGER_TAG);
            continue;
        }
        NSString *newAudioHash=reminder.audioHash;
        NSString *reminderId=reminder.reminder_id;
        NSString *oldAudioHash=NULL;
        if(oldRemindList!=NULL&&[oldRemindList count]>0)
        {
            oldAudioHash=[oldRemindList valueForKey:[NSString stringWithFormat:@"%@",reminderId]];
        }
        if(oldAudioHash==NULL||![oldAudioHash isEqualToString:newAudioHash])
        {
            //取新的提醒文件
            @try {
			
                dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                if(queue==NULL)
                {
                    NSLog(@"%@,getRemindFiles,queue is null",DATAMANAGER_TAG);
                    return;
                }
                dispatch_async(queue, ^{
                    if(reminder.audioUrl!=NULL&&![reminder.audioUrl isEqualToString:@"(null)"]&&![reminder.audioUrl isEqualToString:@""])
                    {
                        //[self getAudioByUrl:newAudioHash url:reminder.audioUrl theUid:reminderId type:REMINDFILE otherId:NULL];
                        [self getAudio:newAudioHash theUid:reminderId type:REMINDFILE otherId:NULL];
                    }
                    else
                    {
                        [self getAudio:newAudioHash theUid:reminderId type:REMINDFILE otherId:NULL];
                    }
                    
                });
                
            }
            @catch (NSException *exception) {
                NSLog(@"%@,getRemindFiles,exception is %@",DATAMANAGER_TAG,[exception reason]);
            }
 
        }
    }
   
}
-(void)getAudioByUrl:(NSString *)audioHash url:(NSString *)url theUid:(NSString *)theUid type:(fileType)type otherId:(NSString *)otherId
{
    NSLog(@"%@,getAudioByUrl entered,url is %@.",SyncManager_TAG,url);
    if(url==NULL||[url isEqualToString:@"(null)"]||[url length]==0)
    {
        NSLog(@"%@,getAudioByUrl,audioHash is illegal.",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        return;
    }
            /*
            dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            if(queue==NULL)
            {
                NSLog(@"%@,getAudioByUrl,queue is null",DATAMANAGER_TAG);
                return;
            }*/
            //dispatch_async(queue, ^{
                //下载文件
                NSString *directoryPath=NULL;
                if(type==REMINDFILE)
                {
                    directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/remind"];
                }
                else if(type==GROUPCHATFILE)
                {
                    directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/chat"];
                }
                else if(type==SINGLEFILE)
                {
                    directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/chat"];
                }
                
                if(![Tooler isDirectoryExist:directoryPath])
                {
                    return;
                }
                NSString *ts=[Tooler getTimeStamp];
                NSString *fileName=[NSString stringWithFormat:@"audio%@%@.amr",theUid,ts];
                NSString *wavName=[NSString stringWithFormat:@"audio%@%@.wav",theUid,ts];
                NSString *filePath=[directoryPath stringByAppendingString:[NSString stringWithFormat:@"/%@",fileName]];
                NSString *wavPath=[directoryPath stringByAppendingString:[NSString stringWithFormat:@"/%@",wavName]];
                BOOL is_downLoad=[self.theRequeseter downLoadFile:url filePath:filePath];
                if(is_downLoad)
                {
                    //把amr转换成wav的
                    if(![VoiceConverter ConvertAmrToWav:filePath wavSavePath:wavPath])
                        return;
                    NSString *fileUrl=NULL;
                    if(type==REMINDFILE)
                    {
                        fileUrl=[NSString stringWithFormat:@"/remind/%@",wavName];
                    }
                    else if(type==GROUPCHATFILE)
                    {
                        fileUrl=[NSString stringWithFormat:@"/chat/%@",wavName];
                    }
                    else
                    {
                        fileUrl=[NSString stringWithFormat:@"/chat/%@",wavName];
                    }
                    
                    //保存到数据库
                    if(type==REMINDFILE)
                    {
                        [self.theManager updateRemindFile:theUid filePath:fileUrl audioHash:audioHash];
                        [[NSNotificationCenter defaultCenter] postNotificationName:SYNCREMINDFILEFINISHED object:nil  userInfo:nil];
                        NSLog(@"%@,getAudioByUrl,send notification:%@",SyncManager_TAG,SYNCREMINDFILEFINISHED);
                    }
                    else if(type==GROUPCHATFILE)
                    {
                        [self.theManager updateGroupChatFile:theUid filePath:fileUrl groupId:otherId];
                        [[NSNotificationCenter defaultCenter] postNotificationName:SYNCCHATDATAFINISHED object:nil  userInfo:nil];
                    }
                    else if(type==SINGLEFILE)
                    {
                        [self.theManager updateSingleChatFile:theUid filePath:fileUrl targetUid:otherId];
                        [[NSNotificationCenter defaultCenter] postNotificationName:SYNCCHATDATAFINISHED object:nil  userInfo:nil];
                    }
                    //删除amr文件
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    NSError *err=nil;
                    [fileManager removeItemAtPath:filePath error:&err];
                    if(err!=nil)
                    {
                        NSLog(@"%@,getAudioByUrl,delete file error,error is %@.",TAG,err);
                    }
                    
                }
                
           // });
}

-(void)getAudio:(NSString *)audioHash theUid:(NSString *)theUid type:(fileType)type otherId:(NSString *)otherId
{
    NSLog(@"%@,getAudio entered,audioHash is %@.",SyncManager_TAG,audioHash);
    if(audioHash==NULL||[audioHash isEqualToString:@"(null)"]||[audioHash length]==0)
    {
        NSLog(@"%@,getAudio,audioHash is illegal.",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getAudio,user is null",SyncManager_TAG);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"fileHash\":\"%@\"}",audioHash];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:data forKey:@"data"];
    [param setValue:@"UserApiImpl.getFileUrl" forKey:@"method"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getAudio,resdict is null",SyncManager_TAG);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            if(queue==NULL)
            {
                NSLog(@"%@,getAudio,queue is null",DATAMANAGER_TAG);
                return;
            }
            dispatch_async(queue, ^{
                
                
            NSString *url=[resdict valueForKey:@"url"];
            if(url==NULL||[url length]<=0)
            {
                NSLog(@"%@,getAudio,url is null.",DATAMANAGER_TAG);
                return;
            }
            //下载文件
            NSString *directoryPath=NULL;
            if(type==REMINDFILE)
            {
                directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/remind"];
            }
            else if(type==GROUPCHATFILE)
            {
                directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/chat"];
            }
            else if(type==SINGLEFILE)
            {
               directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/chat"];
            }
            
            if(![Tooler isDirectoryExist:directoryPath])
            {
                return;
            }
            NSString *ts=[Tooler getTimeStamp];
            NSString *fileName=[NSString stringWithFormat:@"audio%@.amr",ts];
            NSString *wavName=[NSString stringWithFormat:@"audio%@.wav",ts];
            NSString *filePath=[directoryPath stringByAppendingString:[NSString stringWithFormat:@"/%@",fileName]];
            NSString *wavPath=[directoryPath stringByAppendingString:[NSString stringWithFormat:@"/%@",wavName]];
            BOOL is_downLoad=[self.theRequeseter downLoadFile:url filePath:filePath];
            if(is_downLoad)
            {
                //把amr转换成wav的
                if(![VoiceConverter ConvertAmrToWav:filePath wavSavePath:wavPath])
                    return;
                NSString *fileUrl=NULL;
                if(type==REMINDFILE)
                {
                    fileUrl=[NSString stringWithFormat:@"/remind/%@",wavName];
                }
                else if(type==GROUPCHATFILE)
                {
                    fileUrl=[NSString stringWithFormat:@"/chat/%@",wavName];
                }
                else
                {
                    fileUrl=[NSString stringWithFormat:@"/chat/%@",wavName];
                }

                //保存到数据库
                if(type==REMINDFILE)
                {
                    [self.theManager updateRemindFile:theUid filePath:fileUrl audioHash:audioHash];
                    [[NSNotificationCenter defaultCenter] postNotificationName:SYNCREMINDFILEFINISHED object:nil  userInfo:nil];
                    NSLog(@"%@,getAudio,send notification:%@",SyncManager_TAG,SYNCREMINDFILEFINISHED);
                }
                else if(type==GROUPCHATFILE)
                {
                    [self.theManager updateGroupChatFile:theUid filePath:fileUrl groupId:otherId];
                    [[NSNotificationCenter defaultCenter] postNotificationName:SYNCCHATDATAFINISHED object:nil  userInfo:nil];
                }
                else if(type==SINGLEFILE)
                {
                    [self.theManager updateSingleChatFile:theUid filePath:fileUrl targetUid:otherId];
                    [[NSNotificationCenter defaultCenter] postNotificationName:SYNCCHATDATAFINISHED object:nil  userInfo:nil];
                }
                //删除amr文件
                NSFileManager *fileManager = [NSFileManager defaultManager];
                NSError *err=nil;
                [fileManager removeItemAtPath:filePath error:&err];
                if(err!=nil)
                {
                    NSLog(@"%@,getAudio,delete file error,error is %@.",TAG,err);
                }

            }
                
            });
        }
    }];
    
}
/*
 APP向手表发送指令
 */
-(void)sendCommand:(NSString *)deviceUid type:(CommandType)type watchParams:(NSString *)watchParams completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,sendCommand entered. deviceUid is %@,type is %d.",SyncManager_TAG,deviceUid,type);
    if(callback==NULL)
    {
        NSLog(@"%@,sendCommand,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0||type<=0||type>7)
    {
        NSLog(@"%@,sendCommand,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,sendCommand,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=NULL;
    if(type==THEME_CHANGE)
    {
        data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"type\":%d,\"params\":%@}",deviceUid,type,watchParams];
    }
    else
    {

       data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"type\":%d}",deviceUid,type];
    }
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.sendCommand" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,sendCommand,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,sendCommand success.",SyncManager_TAG);
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,sendCommand,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];
}
-(void)getWatchData:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getWatchData entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,getWatchData,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0)
    {
        NSLog(@"%@,getWatchData,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getWatchData,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@}",deviceUid];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getWatchData" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getWatchData,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getWatchData success.",SyncManager_TAG);
            //解析数据
            Watch *watch=[[Watch alloc] init];
            if(watch==NULL)
            {
                NSLog(@"%@,getWatchData,watch is null.",SyncManager_TAG);
                callback(FAIL,NULL,NULL);
                return;
            }
            if([resdict valueForKey:@"battery"]!=NULL)
            {
               watch.battery=[[resdict valueForKey:@"battery"] intValue];
            }
            watch.version=[resdict valueForKey:@"fwVer"];
            watch.deviceUid=deviceUid;
            //更改手表状态
            [self.theManager updateWatchInfo:watch];
            NSDictionary *locationInfo=[resdict valueForKey:@"location"];
            if(locationInfo==NULL||[locationInfo count]==0)
            {
                NSLog(@"%@,getWatchData,locationInfo is null.",SyncManager_TAG);
                callback(FAIL,NULL,NULL);
                return;
            }
            Location *location=[[Location alloc] init];
            if(location==NULL)
            {
                NSLog(@"%@,getWatchData,location is null.",SyncManager_TAG);
                callback(FAIL,NULL,NULL);
                return;
            }
            location.radius=[[locationInfo valueForKey:@"radius"] floatValue];
            location.mainAddress=[locationInfo valueForKey:@"street"];
            location.locateType=[[locationInfo valueForKey:@"locateType"] intValue];
            location.latitude=[[locationInfo valueForKey:@"latitude"] floatValue];
            location.subAddress=[locationInfo valueForKey:@"description"];
            location.longtitude=[[locationInfo valueForKey:@"longtitude"] floatValue];
            location.gen_time=[locationInfo valueForKey:@"createTime"];
            location.deviceUid=deviceUid;
            [self.theManager addLocation:location];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getWatchData,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
    }];

}
-(void)updateSettingParameters:(NSString *)deviceUid  Setting:(Setting *)setting completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,updateSettingParameters entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,updateSettingParameters,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0||setting==NULL)
    {
        NSLog(@"%@,updateSettingParameters,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,updateSettingParameters,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"setting\":{\"type\":%d,\"value\":%d}}",deviceUid,setting.type,setting.value];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.updateSettingParameters" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,updateSettingParameters,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,updateSettingParameters success.",SyncManager_TAG);
            //更新数据库
            [self.theManager updateSetting:setting deviceUid:deviceUid];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,updateSettingParameters,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
}
-(void)getSettingParameters:(NSString *)deviceUid  completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getSettingParameters entered. deviceUid is %@.",SyncManager_TAG,deviceUid);
    if(callback==NULL)
    {
        NSLog(@"%@,getSettingParameters,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||[deviceUid intValue]<=0)
    {
        NSLog(@"%@,getSettingParameters,parameters is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getSettingParameters,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@}",deviceUid];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getSettingParameters" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getSettingParameters,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getSettingParameters success.",SyncManager_TAG);
            //更新数据库
            NSArray *settingData=[resdict valueForKey:@"settings"];
            if(settingData==NULL||[settingData count]==0)
            {
                NSLog(@"%@,getSettingParameters ,settingData is null.",SyncManager_TAG);
                callback(SUCESS,NULL,NULL);
                return;
            }
            NSMutableArray *settingArray=[[NSMutableArray alloc] init];
            if(settingArray==NULL)
            {
                NSLog(@"%@,getSettingParameters ,settingArray is null.",SyncManager_TAG);
                callback(SUCESS,NULL,NULL);
                return;
            }
            for(int i=0;i<[settingData count];i++)
            {
                NSDictionary *settingInfo=[settingData objectAtIndex:i];
                if(settingInfo==NULL||[settingInfo count]==0)
                {
                    NSLog(@"%@,getSettingParameters,settingInfo is null.",SyncManager_TAG);
                    continue;
                }
                Setting *theset=[[Setting alloc] init];
                theset.type=[[settingInfo valueForKey:@"type"] intValue];
                theset.value=[[settingInfo valueForKey:@"value"] intValue];
                if(theset!=NULL)
                {
                    [settingArray addObject:theset];
                    theset=NULL;
                }
            }
            if([settingArray count]>0)
            {
                [self.theManager updateSettingArray:settingArray deviceUid:deviceUid];
            }
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getSettingParameters,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
        
    }];

}
-(void)feedback:(Advice *)advice completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,feedback entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,feedback,callback is null",SyncManager_TAG);
        return;
    }
    if(advice==NULL)
    {
        NSLog(@"%@,feedback,parameter is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,feedback,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"feedback\":{\"contact\":\"%@\",\"advice\":\"%@\"}}",advice.number,advice.content];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.feedback" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,feedback,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,feedback success.",SyncManager_TAG);
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,feedback,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
        
    }];

}
-(void)checkAppVersion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,checkAppVersion entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,checkAppVersion,callback is null",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"https://itunes.apple.com/lookup?id=%@",appId];
    [self.theRequeseter asyncPost:urtStr parameters:NULL completion:^(NSDictionary *resdict)
    {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,checkAppVersion,resdict is null",SyncManager_TAG);
            callback(FAIL,NULL,NULL);
            return;
        }
        //for test
        /*
        NSMutableDictionary *retValue=[[NSMutableDictionary alloc] init];
        [retValue setValue:@"0" forKey:@"isLatest"];
        [retValue setValue:@"www.baidu.com" forKey:@"updateUrl"];
        callback(SUCESS,retValue,NULL);
        */
        NSArray *infoArray=[resdict valueForKey:@"results"];
        if(infoArray==NULL||[infoArray count]==0)
        {
            NSLog(@"%@,checkAppVersion,infoArray is null.",SyncManager_TAG);
            callback(FAIL,NULL,NULL);
            return;
        }
        NSDictionary *releaseInfo=[infoArray objectAtIndex:0];
        if(releaseInfo==NULL||[releaseInfo count]==0)
        {
            NSLog(@"%@,checkAppVersion,releaseInfo is null.",SyncManager_TAG);
            callback(FAIL,NULL,NULL);
            return;
        }
        NSString *latestVersion=[releaseInfo objectForKey:@"version"];
        if(latestVersion==NULL)
        {
            NSLog(@"%@,checkAppVersion,laestVersion is null.",SyncManager_TAG);
            callback(FAIL,NULL,NULL);
            return;
        }
        NSDictionary *info=[[NSBundle mainBundle] infoDictionary];
        if(info==NULL||[info count]==0)
        {
            NSLog(@"%@,checkAppVersion,info is null.",SyncManager_TAG);
            callback(FAIL,NULL,NULL);
            return;
        }
        NSString *currentVersion=[info valueForKey:@"Bundle version"];
        BOOL isLatest=YES;
        if(![currentVersion isEqualToString:latestVersion])
        {
            isLatest=NO;
        }
        NSMutableDictionary *retValue=[[NSMutableDictionary alloc] init];
        Version *version=[[Version alloc] init];
        version.fwVer=latestVersion;
        version.url=[releaseInfo valueForKey:@"trackViewUrl"];
        version.fileSize=[[releaseInfo valueForKey:@"fileSizeBytes"] floatValue];
        [retValue setValue:version forKey:@"version"];
        callback(SUCESS,retValue,NULL);
    }];

}
-(void)deviceUpgrade:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,deviceUpgrade entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,deviceUpgrade,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL)
    {
        NSLog(@"%@,deviceUpgrade,parameter is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,deviceUpgrade,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@}",deviceUid];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.deviceUpgrade" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,deviceUpgrade,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,deviceUpgrade success.",SyncManager_TAG);
            //解析数据并返回给UI
            NSMutableDictionary *retValue=[[NSMutableDictionary alloc] init];
            NSDictionary *versionInfo=[resdict valueForKey:@"deviceVersion"];
            Version *version=[[Version alloc] init];
            if(version!=NULL)
            {
                version.fwVer=[versionInfo valueForKey:@"fwVer"];
                version.desc=[versionInfo valueForKey:@"description"];
                version.createTime=[versionInfo valueForKey:@"createTime"];
                version.fileHash=[versionInfo valueForKey:@"fileHash"];
                version.fileSize=[[versionInfo valueForKey:@"fileSize"] floatValue];
                version.deviceUid=deviceUid;
                [retValue setValue:version forKey:@"version"];
            }
            callback(SUCESS,retValue,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,deviceUpgrade,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
}
/*
-(void)getGroupMembers:(NSString *)groupId completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getGroupMembers entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,getGroupMembers,callback is null",SyncManager_TAG);
        return;
    }
    if(groupId==NULL)
    {
        NSLog(@"%@,getGroupMembers,parameter is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getGroupMembers,user is null",SyncManager_TAG);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *ts=[self.theManager getGroupManagerTS:groupId accountId:uid];
    if([ts isEqualToString:@"(null)"]||ts==NULL||[ts isEqualToString:@""])
    {
        ts=@"null";
    }
    NSString *data=[NSString stringWithFormat:@"{\"groupId\":%@,\"ts\":%@}",groupId,ts];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getGroupMembers" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict)
    {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getGroupMembers,resdict is null",SyncManager_TAG);
            callback(FAIL,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getGroupMembers success.",SyncManager_TAG);
            //解析取到的管理员数据
            NSMutableArray *managerList=[[NSMutableArray alloc] init];
            NSArray *retData=[resdict valueForKey:@"users"];
            NSString *groupId=[resdict valueForKey:@"groupId"];
            NSString *ts=[resdict valueForKey:@"ts"];
            for(int i=0;i<[retData count];i++)
            {
                NSDictionary *managerInfo=[retData objectAtIndex:i];
                if(managerInfo==NULL||[managerInfo valueForKey:@"uid"]==NULL)
                {
                    NSLog(@"%@,getGroupMembers,watchInfo is null,i is %d",SyncManager_TAG,i);
                    continue;
                }
                Manager *manager=[[Manager alloc] init];
                if(manager!=NULL)
                {
                    manager.user_id=[managerInfo valueForKey:@"uid"];
                    manager.phone=[managerInfo valueForKey:@"phoneNum"];
                    manager.alias=[managerInfo valueForKey:@"alias"];
                    manager.photoHash=[managerInfo valueForKey:@"photoHash"];
                    manager.action=[managerInfo valueForKey:@"action"];
                    manager.deviceUid=deviceUid;
                    manager.accountId=uid;
                    manager.type=[Tooler getManagerType:[[managerInfo valueForKey:@"role"] intValue]];
                    manager.groupId=[groupId intValue];
                    manager.birth=[managerInfo valueForKey:@"birthday"];
                    manager.nickName=[managerInfo valueForKey:@"nickName"];
                    manager.update_time=ts;
                    [managerList addObject:manager];
                    manager=NULL;
                }
                
            }
            //管理人员信息，更新到本地数据库
            NSLog(@"%@,getGroupMembers,manager count is %d",DATAMANAGER_TAG,(int)[managerList count]);
            if([managerList count]>0)
            {
                [self.theManager updateManagers:managerList];
            }
            //如果头像发生变化，取新的头像
            [self getManagerPhotos:managerList deviceUid:deviceUid];
            //通知UI
            callback(SUCESS,NULL,NULL);
            
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getGroupMembers,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
}
 */
-(void)updateViceAdminInfo:(NSString *)deviceUid viceAdmin:(Manager *)viceAdmin  completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,updateViceAdminInfo entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,updateViceAdminInfo,callback is null",SyncManager_TAG);
        return;
    }
    if(deviceUid==NULL||viceAdmin==NULL||viceAdmin.user_id==NULL)
    {
        NSLog(@"%@,updateViceAdminInfo,parameter is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,updateViceAdminInfo,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"viceAdmin\":{\"viceAdminUid\":%@,\"alias\":\"%@\",\"isSos\":%d}}",deviceUid,viceAdmin.user_id,viceAdmin.alias,viceAdmin.isSos];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.updateViceAdminInfo" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,updateViceAdminInfo,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,updateViceAdminInfo success.",SyncManager_TAG);
            //更改数据库
            [self.theManager updateViceAdminInfo:viceAdmin deviceUid:deviceUid];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,updateViceAdminInfo,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
}
-(void)confirmPushMessage:(NSString *)rid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,confirmPushMessage entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,confirmPushMessage,callback is null",SyncManager_TAG);
        return;
    }
    if(rid==NULL)
    {
        NSLog(@"%@,confirmPushMessage,parameter is illegal",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,confirmPushMessage,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"rid\":%@}",rid];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.confirmPushMessage" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,confirmPushMessage,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,confirmPushMessage success.",SyncManager_TAG);
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,confirmPushMessage,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
}
-(void)setTcpDisconnect:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,setTcpDisconnect entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,setTcpDisconnect,callback is null",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,setTcpDisconnect,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    NSString *iosToken=mydelegate.iosToken;
    NSString *data=[NSString stringWithFormat:@"{\"token\":\"%@\"}",iosToken];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.setTcpDisconnect" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,setTcpDisconnect,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,setTcpDisconnect success.",SyncManager_TAG);
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,setTcpDisconnect,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
        
    }];
}

-(void)phoneLogout:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,phoneLogout entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,phoneLogout,callback is null",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,phoneLogout,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    NSString *iosToken=mydelegate.iosToken;
    NSString *data=[NSString stringWithFormat:@"{\"token\":\"%@\"}",iosToken];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.phoneLogout" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,phoneLogout,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,phoneLogout success.",SyncManager_TAG);
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,phoneLogout,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
        
    }];
}

-(void)getUserInfo:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback
{
    NSLog(@"%@,getUserInfo entered.",SyncManager_TAG);
    if(callback==NULL)
    {
        NSLog(@"%@,getUserInfo,callback is null",SyncManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getUserInfo,user is null",SyncManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getUserInfo" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getUserInfo,resdict is null",SyncManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getUserInfo success.",SyncManager_TAG);
            NSDictionary *userInfo=[resdict valueForKey:@"userInfo"];
            if(userInfo!=NULL)
            {
                user.nickName=[userInfo valueForKey:@"nickName"];
                user.birth=[NSString stringWithFormat:@"%@",[userInfo valueForKey:@"birthday"]];
                [self.theManager updateUser:user];
                NSString *newPhotoHash=[userInfo valueForKey:@"photoHash"];
                if(user.photoHash==NULL||![user.photoHash isEqualToString:newPhotoHash])
                {
                    NSString *url=[userInfo valueForKey:@"url"];
                    if(url!=NULL&&![url isEqualToString:@"(null)"]&&![url isEqualToString:@""])
                    {
                         //[self getPhotoByUrl:newPhotoHash url:url theUid:user.uid type:USER];
                        [self getPhoto:newPhotoHash theUid:user.uid type:USER];
                    }
                    else
                    {
                        [self getPhoto:newPhotoHash theUid:user.uid type:USER];
                    }

                }
            }
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getUserInfo,fail,error code is %@",SyncManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];

}


-(void)getWatchPhotos
{
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        return;
    }
    NSArray *photoHashLists=[self.theManager getFailWhatchPhotoHash];
    if(photoHashLists==NULL||[photoHashLists count]==0)
        return;
    for(int i=0;i<[photoHashLists count];i++)
    {
        NSDictionary *hashInfo=[photoHashLists objectAtIndex:i];
        if(hashInfo==NULL||[hashInfo count]==0)
            continue;
        NSString *deviceUid=[hashInfo valueForKey:@"deviceUid"];
        NSString *photoHash=[hashInfo valueForKey:@"photoHash"];
        if(deviceUid!=NULL&&photoHash!=NULL&&![photoHash isEqualToString:@"(null)"]&&![photoHash isEqualToString:@""])
        {
            [self getPhoto:photoHash theUid:deviceUid type:WATCH];
        }
        
    }
    
}
-(void)getManagerPhotos:(NSString *)deviceUid
{
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        return;
    }
    NSArray *photoHashLists=[self.theManager getFailManagerPhotoHash:deviceUid];
    if(photoHashLists==NULL||[photoHashLists count]==0)
        return;
    for(int i=0;i<[photoHashLists count];i++)
    {
        NSDictionary *hashInfo=[photoHashLists objectAtIndex:i];
        if(hashInfo==NULL||[hashInfo count]==0)
            continue;
        NSString *userId=[hashInfo valueForKey:@"user_id"];
        NSString *photoHash=[hashInfo valueForKey:@"photoHash"];
        if(deviceUid!=NULL&&photoHash!=NULL&&![photoHash isEqualToString:@"(null)"]&&![photoHash isEqualToString:@""])
        {
            [self getPhoto:photoHash theUid:userId type:MANAGER];
        }
        
    }
    
}
-(void)getContactPhotos:(NSString *)deviceUid
{
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        return;
    }
    NSArray *photoHashLists=[self.theManager getFailContactPhotoHash:deviceUid];
    if(photoHashLists==NULL||[photoHashLists count]==0)
        return;
    for(int i=0;i<[photoHashLists count];i++)
    {
        NSDictionary *hashInfo=[photoHashLists objectAtIndex:i];
        if(hashInfo==NULL||[hashInfo count]==0)
            continue;
        NSString *userId=[hashInfo valueForKey:@"user_id"];
        NSString *photoHash=[hashInfo valueForKey:@"photoHash"];
        if(deviceUid!=NULL&&photoHash!=NULL&&![photoHash isEqualToString:@"(null)"]&&![photoHash isEqualToString:@""])
        {
            [self getPhoto:photoHash theUid:userId type:PHONECONTACT];
        }
        
    }
    
}

@end
